0

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();
    }
});
Elkazi
  • 167
  • 1
  • 9
  • 1
    `querySelectorAll('.stop').forEach(close => close.addEventListener(....))`. – Yousaf Jun 22 '21 at 06:56
  • What problem are you having? Your code looks like it should work (though you shouldn't be using `onclick`, you should always only ever use `addEventListener`. – Dai Jun 22 '21 at 06:56
  • 1
    `for( const el of document.QuerySelectorAll('.stop') ) el.addEventListener('click', e => e.currentTarget.pause() );`. – Dai Jun 22 '21 at 06:57
  • If I understand your question, then this should be what you are after: [JavaScript click event listener on class](https://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class) – Nick Parsons Jun 22 '21 at 06:58
  • The problem is the video keep playing in the background, I want to add classes to multiple elements "div" and whenever I click on the element with class "stop" I want it the stop the video. – Elkazi Jun 22 '21 at 07:42

2 Answers2

1

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
  }
})
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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();
        })
    })
Elkazi
  • 167
  • 1
  • 9