What is this piece of Javascript for Isotope filter doing?

Tags:



I am having some trouble understanding what is happening in a piece of vanilla JS for the Isotope filter. The original code is here: https://codepen.io/desandro/pen/VWLJEb

var buttonGroups = document.querySelectorAll('.button-group');

for (var i = 0; i < buttonGroups.length; i++) {
  var buttonGroup = buttonGroups[i];
  var onButtonGroupClick = getOnButtonGroupClick(buttonGroup);
  buttonGroup.addEventListener('click', onButtonGroupClick);
}

function getOnButtonGroupClick(buttonGroup) {
  return function(event) {
    // check for only button clicks
    var isButton = event.target.classList.contains('button');
    if (!isButton) {
      return;
    }
    var checkedButton = buttonGroup.querySelector('.is-checked');
    checkedButton.classList.remove('is-checked')
    event.target.classList.add('is-checked');
  }
}

What is happening between the getOnButtonGroupClick function and it being assigned to a variable in the for loop preceding it?

Answer

getButtonGroupClick returns a closure that saves the value of buttonGroup. When you click on a button in the button group, it uses that closure variable to search for the checked button in the group, uncheck it, and then check the button you clicked on.

This complexity isn’t really needed. When an event listener is called, event.currentTarget is set to the element that the listener was attached to, so you could just use that.

var buttonGroups = document.querySelectorAll('.button-group');

for (var i = 0; i < buttonGroups.length; i++) {
  var buttonGroup = buttonGroups[i];
  buttonGroup.addEventListener('click', onButtonGroupClick);
}

function OnButtonGroupClick(event) {
  // check for only button clicks
  var isButton = event.target.classList.contains('button');
  if (!isButton) {
    return;
  }
  var checkedButton = event.currentTarget.querySelector('.is-checked');
  checkedButton.classList.remove('is-checked')
  event.target.classList.add('is-checked');
}


Source: stackoverflow