简体   繁体   中英

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

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 class="hover-scale rounded mb-0 ratio ratio-1x1">
    <a class="thumbnail-wrapper" href=".........">
        <video class="3c4c0f2d-6324-48c3-b32b-08d9c0b035e0 loaded" data-src="......." data-was-processed="true" loop="" preload="metadata" src="........" width="100%">
            <source src=".........." type="video/mp4">
        </video>
    </a>
    <p>
        <i class="uil uil-play text-white fs-20 video-play-button 3c4c0f2d-6324-48c3-b32b-08d9c0b035e0"></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?

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();
});

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