Ryan Karpeles Ryan Karpeles - 1 month ago 15
Javascript Question

Play multiple videos on page with jQuery each() function

I have a page with multiple HTML5 videos on it. For each video, there is a "poster" image that sits on top of the video. When someone clicks the poster image, the image disappears via CSS, and the video below it plays.

My problem is that I can only get the FIRST video on the page to play when someone clicks it. I'd like the user to be able to click any of the videos on the page to play them. My guess is that I somehow need to incorporate the "each()" function into the jQuery code.

Here is my current jQuery code:

$('#videocover').click(function() {
var video = $('#wp_mep_1').get(0);
video.play();

$(this).css('visibility', 'hidden');
return false;
});


Below is a JSFiddle with multiple videos on the page, but only the first one working when you click it. Feel free to play around:
https://jsfiddle.net/rtkarpeles/ammebd3k/3/

Thanks in advance for any and all help you can provide!

Answer

You cannot have multiple elements with same ID. Change them to class.

Change the video-container from ID to class and videocover as well.

<div class="video-container">
  <video>...</video>
  <div class="videocover"></div>
</div>

With the above structure the below script should work fine.

$('.videocover').click(function () {
    var video = $(this).closest('.video-container').find('video')[0]; 
    video.play();

    $(this).css('visibility', 'hidden');
    return false;
});

.closest() will fetch the first match when traversing through ancestors in DOM

Here is a demo https://jsfiddle.net/dhirajbodicherla/ammebd3k/5/