View on GitHub


a bunch of vanilla JS practice projects based on JavaScript 30 by WesBos.


demo gif

Back to home page

User stories


Check multiple checkboxes with Shift key

We want to check every checkboxes in between only if the Shift key is pressed. How we do that is by keeping track of the previous checkbox(the one we just checked) and using a Boolean value as a flag.

let lastChecked;

function handleCheck(e) {
 let inBetween = false;
 //if Shift key is held and user is checking the current checkbox
 if (e.shiftKey && this.checked) {
  checkboxes.forEach(checkbox => {
   //loop through every checkbox
   //if it is the current or the previous checkbox
   if (checkbox === this || checkbox === lastChecked) {
    //set the inBetween to true
    inBetween = !inBetween;
   if (inBetween) {
    //check the box if inBetween is true
    checkbox.checked = true;
 lastChecked = this; //the current checkbox will now be the previous checkbox

A simple sketch helps visualizing the process:

sketch for visualizing the code

Clear and reverse checkboxes

Since we know that checkbox.checked means the checking status of checkboxes, we can now reverse it or set it to false to clear all the check.

const checkboxes = document.querySelectorAll(".checkbox");
const btnReverse = document.querySelector(".btn_reverse");
const btnClear = document.querySelector(".btn_clear");

checkboxes.forEach(checkbox => checkbox.addEventListener("click", handleCheck));
btnReverse.addEventListener("click", () => {
 checkboxes.forEach(checkbox => (checkbox.checked = !checkbox.checked));
btnClear.addEventListener("click", () => {
 checkboxes.forEach(checkbox => (checkbox.checked = false));