Week 7: Array Methods and Iterators

To Do This Week:

Assignments:

You'll receive a provided HTML/CSS structure containing an image slider and an animated navigation menu. Your task is to write the JavaScript that makes the interface work — and to be able to explain every part of it.

Read (Optional!): Chapters from Eloquent JavaScript:

Upcoming Assignments


Student Projects:

Abbas

Andrew

Challenge: Volume Knob

  1. describe what should happen in plain English.
  2. write numbered logic steps as a comment.
  3. turn one step at a time into JavaScript. Test after each step.
  4. console.log() your variables so you can see what the program is thinking.

Two buttons turn a "volume" up and down between 0 and 10. The number shows on the page. At 0 the label says Muted; at 8 or higher it says Loud! and turns red. The volume can never go below 0 or above 10.

Copy starter HTML into a new .html file and open it in the browser with the Console open.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; text-align: center; padding: 40px; }
    #level { font-size: 80px; margin: 10px; }
    .loud { color: red; }
    button { font-size: 24px; padding: 10px 20px; }
  </style>
</head>
<body>
  <h1>Volume</h1>
  <p id="level">5</p>
  <p id="label"></p>
  <button id="down">−</button>
  <button id="up">+</button>

  <script>
  /*
    1. Store the volume in a variable (start at 5).
    2. Select the level text, the label, and both buttons.
    3. Write updateDisplay(): put the volume on the page;
       if 0 → "Muted"; if 8 or more → "Loud!" + add class "loud";
       otherwise → clear the label and remove "loud".
    4. Write volumeUp(): if volume is less than 10, add 1. Then updateDisplay().
    5. Write volumeDown(): if volume is more than 0, subtract 1. Then updateDisplay().
    6. Add click listeners to the buttons.
    7. Call updateDisplay() once so the page starts correct.
  */

  </script>
</body>
</html>
let volume = 5;

const level = document.querySelector("#level");
const label = document.querySelector("#label");
const upBtn = document.querySelector("#up");
const downBtn = document.querySelector("#down");

function updateDisplay() {
  level.textContent = volume;
  console.log("volume is", volume);

  if (volume === 0) {
    label.textContent = "Muted";
    level.classList.remove("loud");
  } else if (volume >= 8) {
    label.textContent = "Loud!";
    level.classList.add("loud");
  } else {
    label.textContent = "";
    level.classList.remove("loud");
  }
}

function volumeUp() {
  if (volume < 10) {
    volume++;
  }
  updateDisplay();
}

function volumeDown() {
  if (volume > 0) {
    volume--;
  }
  updateDisplay();
}

upBtn.addEventListener("click", volumeUp);
downBtn.addEventListener("click", volumeDown);

updateDisplay();

Challenge: Color Buttons

Goal: Make the color of the button you click become the color of the display box.

There are many ways to solve this. You could give every button its own id and write a separate event listener for each one. That works, but it repeats the same kind of code over and over.

Instead, we are going to look for the repeated pattern and use a loop to work through all of the buttons.

Think Through the Problem First

Before writing JavaScript syntax, describe what the program needs to do in normal human language.

  1. Find the display box.
  2. Find all of the color buttons.
  3. Go through the buttons one at a time.
  4. Make each button listen for a click.
  5. When a button is clicked, find out what color that button represents.
  6. Send that color to a function.*
  7. Have the function change the display box to that color.

Translate the Human Steps into JavaScript Logic

Now describe the same process using JavaScript ideas, but do not worry about exact syntax yet.

  1. Create a variable that refers to the display element.
  2. Create a variable that contains all of the buttons.
  3. Loop through the collection of buttons.
  4. For each button, attach a click event listener.
  5. Inside the event listener, get the color from the current button.
  6. Call a function and pass the color into it as a parameter.
  7. Inside the function, use the parameter to change the display element's CSS.

*Note: You do not technically need a separate function to change the display color. The DOM changes could happen directly inside the click event listener. In this challenge, we will move those changes into a separate function so we can practice functions with parameters and see how a value can be passed from an event into another part of the program.

When JavaScript selects several elements with querySelectorAll(), it gives you a collection that works much like an array. The first element is at index 0, the second is at index 1, and so on.

buttons[0]
buttons[1]
buttons[2]
buttons[3]

This is why a for loop is useful: the variable i can act as both a counting number and the index of the current button.

After we solve the problem with a for loop, we can ask whether we actually need the counting number. If all we want is to do the same thing to every button, forEach() gives us the current button directly.

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: sans-serif;
      text-align: center;
      padding: 40px;
    }

    #display {
      width: 300px;
      height: 200px;
      margin: 30px auto;
      background-color: lightgray;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32px;
    }

    button {
      font-size: 18px;
      padding: 10px 20px;
    }
  </style>
</head>

<body>

  <h1>Choose a Color</h1>

  <div id="display">Choose a color</div>

  <button class="colorButton">tomato</button>
  <button class="colorButton">gold</button>
  <button class="colorButton">skyblue</button>
  <button class="colorButton">seagreen</button>

  <script>

  /*
    HUMAN DESCRIPTION

    1. Find the large display box.
    2. Find all of the color buttons.
    3. Go through the buttons one at a time.
    4. Make each button listen for a click.
    5. When a button is clicked, find out which color
       that button represents.
    6. Send that color to a function.
    7. The function changes the background color of the box
       and puts the color name inside it.
  */

  /*
  JAVASCRIPT LOGIC

  1. Create a variable for the display box.
  2. Create a variable that contains all of the color buttons.
  3. Loop through the buttons one at a time.
  4. Add a click event listener to each button.
  5. When a button is clicked, get that button's color.
  6. Pass the color into a function as a parameter.
  7. In the function, change the display box's background color
     and text using that parameter.
*/


  </script>

</body>
</html>
Solution 1: Using a for loop
<script>

const display = document.querySelector("#display");
const buttons = document.querySelectorAll(".colorButton");

function changeColor(color) {
  display.style.backgroundColor = color;
  display.textContent = color;

  console.log("new color:", color);
}

for (let i = 0; i < buttons.length; i++) {

  buttons[i].addEventListener("click", function() {

    const color = buttons[i].textContent;

    console.log("button index:", i);
    console.log("color:", color);

    changeColor(color);

  });

}

</script>
Solution 2: Using forEach()
<script>

const display = document.querySelector("#display");
const buttons = document.querySelectorAll(".colorButton");

function changeColor(color) {
  display.style.backgroundColor = color;
  display.textContent = color;
}

buttons.forEach(function(button) {

  button.addEventListener("click", function() {

    const color = button.textContent;
    changeColor(color);

  });

});

</script>

Review JavaScript and the DOM:

Traversing // get to elements on the page

Creating & Adding Elements // create new elements and add them to the page

Forms: Accessing Values

JavaScript Methods (in-built functions):

Math Methods:

Switch vs Conditionals


// Example using switch
let day = 3;

switch (day) {
 case 1:
  console.log("Monday");
  break;
 case 2:
  console.log("Tuesday");
  break;
 case 3:
  console.log("Wednesday");
  break;
 default:
  console.log("Other day");
}
// Example using else if let day = 3;

if (day === 1) {
  console.log("Monday");
} else if (day === 2) {
  console.log("Tuesday");
} else if (day === 3) {
  console.log("Wednesday");
} else {
  console.log("Other day");
}

Array Methods

Array Iterators

forEach() (very useful)

forEach() - w3schools
forEach() Demo

Use forEach() when you simply want to do the same thing to every item in a list. Use a for loop when you need more control over the loop. One advantage of a for loop is that the variable i gives you a counting number that can also be used as the index of the current item.


Slider/Menu Site: 5% DUE: 10/7 

You will receive a provided HTML and CSS structure containing an image slider and animated navigation menu. Your task is to write the JavaScript that makes the interface work.

This is primarily a logic and problem-solving project. You should be able to explain how each event, function, variable, and state change contributes to the slider and menu behavior. Think as an interaction designer: this is a showpiece for your portfolio.

Minimum Requirements

Logic Steps (required)

At the top of your <script>, before any code, write your numbered logic steps as a commented list. For example:

/*
  1. Select all the slides and store the current index (start at 0).
  2. Write showSlide(index): hide all slides, show the one at index.
  3. nextSlide(): add 1 to the index; if past the end, loop to 0; showSlide.
  4. prevSlide(): subtract 1; if below 0, loop to the last; showSlide.
  5. Add click listeners on the next and prev buttons.
  6. Toggle the menu open/closed on the menu button click.
*/