userNotFound
userNotFound

Reputation: 13

JS click event on multiple classes

A little stuck here with the following code that works opening a modal on click with the class name '.pl-modal', however when using the class in multiple places it only works on the first element.

I'd like to understand why it doesn't work on multiple elements with the same class.

let player = null;
const $ = function (el) {
  return document.querySelector(el);
};
$(document).on("click", function () {
  $(".pl-modal").classList.add("pl-modal-active");
  player.playVideo();
},false);

function popupClose() {
  $(".pl-modal").classList.remove("pl-modal-active");
  $(".pl-hidden").style.display = "block";
  player.stopVideo();
  player.setPlaybackRate(1);
}
window.onclick = function (event) {
  if (event.target == $(".pl-modal")) {
    popupClose();
  }
};

Upvotes: 0

Views: 2643

Answers (2)

Omri Attiya
Omri Attiya

Reputation: 4037

Use query selector all and foreach:

document.querySelectorAll('.class1').forEach(element => element.addEventListener('click', event => {
  console.log(event.target.innerText);
}));
<div class="class1">text1</div>
<div class="class1">text2</div>
<div class="class1">text3</div>

Read here for more

Upvotes: 1

Eugen Spinne
Eugen Spinne

Reputation: 83

You have to use document.querySelectorAll instead of document.querySelector. querySelector only returns the first element.

Upvotes: 0

Related Questions