Ryan Karpeles Ryan Karpeles - 10 months ago 47
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);

$(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:

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

Answer Source

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">
  <div class="videocover"></div>

With the above structure the below script should work fine.

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

    $(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/