Elkazi
Elkazi

Reputation: 177

How to select multiple classes with the same name and fire the same function?

How to make this function select all class ".stop" and when we click on the element that has this class stop the video?

window.addEventListener("load", function(event) {
    window.addEventListener('scroll', checkScroll, false);
    window.addEventListener('resize', checkScroll, false);

    let playvideo = document.querySelector('video');

    let close = document.querySelector('.stop');


    close.onclick = () => {
        playvideo.pause();
    }
});

Upvotes: 0

Views: 388

Answers (2)

Elkazi
Elkazi

Reputation: 177

Thank you, everyone, for the help, I used this script and it's work as I want

    let playvideo = document.querySelector('video');

    document.querySelectorAll('.stop').forEach(item => {
        item.addEventListener('click', event => {
            //handle click
            playvideo.pause();
        })
    })

Upvotes: 0

mplungjan
mplungjan

Reputation: 177860

Delegate

const container = document.getElementById('videoContainer'); // or whatever you have
container.addEventListener('click',e => {
  const tgt = e.target;
  if (tgt.classList.contains('stop')) {
    tgt.closest('div').querySelector('video').pause(); // assuming the stop is in the same div
  }
})

Upvotes: 1

Related Questions