简体   繁体   中英

How to pause/play html5 videos individually

I have a page with a list of videos. I would like to add a pause/play button to each of them, so that they can be controlled individually.

I can't seem to make it work, though. Each video have this markup:

<div class="media-container">
  <button class="pause-play" type="button">Pause/play</button>
  <div class="video">
    <video playsinline loop muted autoplay>
      <source src="https://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
    </video>
  </div>
</div>

Here's what I have tried:

onload = e => {
  const containers = Array.prototype.slice.apply(document.querySelectorAll('.media-container'));
  containers.forEach(container => {
    const video = container.querySelector('video');
    const playButton = container.querySelector('.pause-play');
    playButton.addEventListener('click', e => {
      //Pause this individual video...? video.pause();
    })
  })
}

The error I get is: Uncaught TypeError: Cannot read property 'addEventListener' of null

JsFiddle here

jQuery is an option as well...

As you say I would like to add , I guess that .pause-play button is not in the page (or maybe it's in the page but not inside .media-container ), so rather than grabbing a reference to an existing element:

const playButton = container.querySelector('.pause-play');

You should be creating one:

const playButton = document.createElement('BUTTON');
playButton.className = 'pause-play';
playButton.addEventListener('click', () => { ... });
container.appendChild(playButton);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM