JavaScript breakdown

·

2 min read

const container = document.querySelector('.container');
const sizeCards = document.querySelectorAll('.size-card');
const place = document.querySelector('.info .place span');
const size = document.querySelector('.info .size span');
const successMsg = document.querySelector('.success-msg');
const continueBtn = document.querySelector('.container button');

sizeCards.forEach((card) => {
    card.addEventListener('click', () => {
        sizeCards.forEach(c => c.classList.remove('active'));
        card.classList.add('active');
    });
})

continueBtn.addEventListener('click', () => {
    const selectedPlace = document.querySelector('.options input[type="radio"]:checked');
    const selectedSize = document.querySelector('.sizeCard input[type="radio"]:checked');
    container.classList.add('hide');
    successMsg.classList.remove('hide');
    place.textContent = selectedPlace.value;
    size.textContent = selectedSize.value + " people";
});

This code block is a part of the JavaScript code snippet that deals with adding interactivity to the size cards on the page.

sizeCards is a NodeList containing all elements with the class name 'sizeCard'. The forEach method is called on the sizeCards NodeList, which loops through each card in the NodeList.

Inside the loop, an anonymous arrow function is defined that takes a single argument card, which represents the current size card element in the iteration.

For each size card, a 'click' event listener is added using the addEventListener method. This event listener is also an anonymous arrow function with no arguments.

When a size card is clicked, the following actions occur within the event listener:

  1. Another forEach loop is called on the sizeCards NodeList. This loop iterates through each size card again, but this time it's used to remove the 'active' class from all size cards. This is done using the classList.remove() method, which removes the specified class from the element's class list. In this case, it removes the 'active' class.
sizeCards.forEach(c => c.classList.remove('active'));
  1. After removing the 'active' class from all size cards, the 'active' class is added to the clicked card using the classList.add() method. This visually highlights the clicked size card and indicates that it is the currently selected size.
card.classList.add('active');

In summary, this code block adds interactivity to the size cards, allowing users to select a size card by clicking on it. When a size card is clicked, it becomes 'active' (highlighted), and any previously active size card is deselected (unhighlighted).