Home > Mobile >  How to play multiple HTML5 videos using individual play buttons with an ID
How to play multiple HTML5 videos using individual play buttons with an ID

Time:12-22

I have a list of HTML5 videos that also have a play button.

Each play button has a unique identifier (as a class name), and then each video has a matching class name, so that I can assign a specific button to a specific video for playback.

HTML

<figure >
    <a  href=".........">
        <video  data-src="......." data-was-processed="true" loop="" preload="metadata" src="........" width="100%">
            <source src=".........." type="video/mp4">
        </video>
    </a>
    <p>
        <i ></i>
    </p>
</figure>

Javascript

var videoPlayBackBtn = document.getElementsByClassName('video-play-button');
for (let item of videoPlayBackBtn) {
    console.log(item.id);
    item.addEventListener('click', function(){
        console.log(this);
    })
}

With the above JS I am able to get the identifier used for the video, and I wish to simply play the video with the matching identifier as the play button, and pause any other videos that don't match. How can I target a specific video in this scenario?

CodePudding user response:

While it would be possible to dissect the class string of the i element to find the video matching that GUID and set it playing, that would be an incredibly brittle way to achieve your goal and would result in some really ugly and unnecessary code.

The simpler way to achieve your goal is to traverse the DOM to find the video related to the i. As you've tagged the question with 'jQuery' this becomes a single handler for all instances of this structure in your HTML:

const $videos = $('figure video');

$('.video-play-button').on('click', e => {
  let $video = $(e.target).closest('figure').find('video');
  $videos.not($video).each((i, v) => v.pause());
  $video[0].play();
});
  • Related