TL;DR: I'd like each YouTube video on this page to act like the first one - autoplay when you expand the content block, pause when you close it. Source has the commented-out dev code included.
I'm working on a page which has multiple divs with hidden content. Each div includes a YouTube video that need to pause when the content hides again. Using the normal embed code, you can't do this, so I'm using the YouTube Javascript API.
To load the array of videos and create each controller, I found this SO post and used it's example to fill the array and store the data. Each <iframe>
is created successfully, and now I'm running into an issue with the controller.
I've created a function, playMedia()
, which is called at the end of the script which displays the content:
$(".title").click(function() {
var clickedPost = $(this).parent();
$('.post').not($(this).parent()).removeClass('active');
clickedPost.toggleClass('active', 500);
playMedia();
});
In the function, I need it to:
- Check that the div is active
- Target the iframe child
- Autoplay when the div is opened, pause when closed.
Here's what I've tried:
function playMedia() {
// Set the ID of the controller to target
var playerId = $(".post.active > iframe").attr('id');
console.log(playerId); // returns undefined
if ($('.title').parent().hasClass('active')) {
playerId.playVideo();
}
}
I have a hunch that it's in how I'm trying to target the active iframe
, but I can't - for the life of me - figure out where the error is. Other eyes are appreciated.