0

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:

  1. Check that the div is active
  2. Target the iframe child
  3. 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.

Community
  • 1
  • 1
Brian
  • 4,274
  • 2
  • 27
  • 55
  • If playerId is undefined then your selector is wrong. Also, playerId will just be a string, which doesn't have a playVideo() function in it. – samuraisam Oct 29 '14 at 01:44
  • Really? I just double checked, and it worked as expected. Does that mean it has something to do with the timing and order the scripts are loading? – Brian Oct 29 '14 at 01:45
  • Ok, I guess I don't understand how that API is called then...I thought the playerId was used to target the element for `playVideo()`. I'll go back and read the docs again. – Brian Oct 29 '14 at 01:49
  • In jQuery, `.attr('anyAttributeName')` will return the value of that attribute. – samuraisam Oct 29 '14 at 01:52

0 Answers0