JavaScript 30- Day 10 Study Notes

Jeffrey Amen
2 min readNov 22, 2020

--

https://javascript30.com/

Day 10 of JavaScript 30 by Wes Bos had a project that worked with checkboxes. The program allowed the user to check off multiple checkboxes by holding the shift key down.

As usual, Bos had set up the HTML and added some basic CSS. The lesson is typically a code-along, but this time he challenged us to get the JavaScript programming started without his help. Herein lies the inherent disadvantage of code-along type lessons; the student can get lazy. I certainly did. My first look at the empty script tag and I drew a complete blank as to what to do first.

Let’s see. Add event listener. Okay, how do I do that? I initially forgot about the input. How do I get the input? It was too easy to restart the video and see how Bos did it.

Get the input.

const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');

Add event listener.

checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));

Now, Bos showed us how to handle the main challenge of the program. Including the input from the checkboxes in between the first and last box checked. He did it all with one function. First, he named a variable outside the function.

let lastChecked;function handleCheck(e){

Next, he set another variable inside the function that was a boolean representing checkboxes between the first and last box checked.

let inBetween =false; //flag variable

The function checked to see if a checkbox was checked, as it looped through.

if(e.shiftKey && this.checked){   //loop over every single checkbox   checkboxes.forEach(checkbox => {        // this = box checked, or last checked box        if(checkbox ===this || checkbox === lastChecked){           inBetween = !inBetween;         }        if(inBetween){          checkbox.checked = true;         }   })  }lastChecked = this;}

A nice, simple program. Using a flag variable is new to me. It is similar to using the toggle method. And of course, this would be used as part of a larger program to input checkbox data.

Follow my blog as I complete the JavaScript 30 course by Wes Bos.

--

--

Jeffrey Amen

Retired physician, writer, aspiring website designer and developer