I have some code that shows a cover image over a video, upon clicking said image it auto plays the video. Currently this code works for one video on one page (because it uses ID's).
The code is leaning on Froogaloop to control and play Vimeo.
Using jQuery how can I convert the following code so that it will work with more than 1 video on a page (currently it breaks):
// Control Vimeo videos
var iframe = document.getElementById('video');
// $f == Froogaloop
var player = $f(iframe);
var playButton = document.getElementById("play-me");
playButton.addEventListener("click", function() {
player.api("play");
$('.bg-image').addClass('hide-me');
setTimeout(function(){
$('.bg-image').css('z-index','-1');
}, 1000);
});
This is my HTML:
<div class="video-wrapper">
<div class="bg-image" id="play-me">
<span class="play">
<i class="i-play"></i>
</span>
</div>
<iframe src="" id="video"></iframe>
</div>
Conver ids to classes:
<div class="video-wrapper">
<div class="bg-image" class="play-me">
<span class="play">
<i class="i-play"></i>
</span>
</div>
<iframe src="" class="video"></iframe>
</div>
and modify your js/jquery to this:
var playButton = $(".play-me");
playButton.get(0).addEventListener("click", function() {
var iframe = $(this).next('.video').get(0),// or use closest() based on your condition
player = $f(iframe);
player.api("play");
$(this).addClass('hide-me');
setTimeout(function(){
$(this).css('z-index','-1');
}, 1000);
});
IF
you had to add more videos inside the same .video-wrapper
, use .closest()
as i commented in top otherwise .next()
will works fine.
Explanation:
With using $(this)
make us confident that code will do changes just on that element we clicked not all.