jdip88
jdip88

Reputation: 447

How to make a video stop when a user clicks away from it?

I have two divs that are hidden and when you click on one of the two buttons, I change that display none to display block and make the video available to play.

  .row.hidden.overflowHidden(data-park="hollywood")
        .col2-3.title(style="padding:0px;")
          div(style="padding:27px;")
            h3 Get the star treatment!
            h2 Universal Studios Hollywood™
          //- .videoContainer.mobilehide
          //-   iframe( class="videoClass mobilehide" src='https://www.youtube.com/embed/xRUDijZgyHc?rel=0', frameborder='0', allowfullscreen='')
          div
            iframe( height="400" width="100%" src='https://www.youtube.com/embed/xRUDijZgyHc?rel=0', frameborder='0', allowfullscreen='')
        .details.col1-3
          div
            h4 You could win a 3-night trip for four.
            p Prize includes:
            ul
              li Round-trip airfare to Los Angeles, California 
              li Ground transportation between the airport and hotel in Los Angeles
              li General Admission tickets for four to Universal Studios Hollywood™ theme park
              li Hotel accommodations

this is one of the videos examples, and when I click the other link it turns that block back to display hidden and the next video to display block. But the one that switches to display hidden continues to play in the back.

Is there any way to stop that video when the user clicks on the next video and switches that video back to display hidden?

Upvotes: 0

Views: 1191

Answers (2)

Adam
Adam

Reputation: 151

Since your video is an embedded YouTube video, you can take advantage of YouTube's iframe javascript API...

Append ?enablejsapi=1 to your embed link:

src='https://www.youtube.com/embed/xRUDijZgyHc?rel=0&enablejsapi=1'

Then, keep track of the video element that is initially clicked on in a variable from within a click event handler:

// You might consider giving your iframe elements a specific ID or class for more precise selection var player = document.getElementsByTagName("div iframe")[0];

When the next video is clicked on, call:

player.pauseVideo();

Upvotes: 1

Racil Hilan
Racil Hilan

Reputation: 25341

To stop the playing video, you can use the pause() method on it. And if you want to rewind it to the beginning too, use the currentTime property.

Example:

var video = document.getElementById("myVideoPlayer");
video.pause();
video.currentTime = 0;

Upvotes: 1

Related Questions