Pause (or play) embedded YouTube video’s with Javascript

First, make sure the embedded video has the following parameter set to 1, like so:

//www.youtube.com/embed/gzDS-Kfd5XQ?enablejsapi=1

Or if it’s not the first parameter, replace the question mark with an ampersand, like so //www.youtube.com/embed/gzDS-Kfd5XQ?rel=0&enablejsapi=1   Now, when you blend in the video with some fancy effect (div sliding upwards, fading or bounce) and want it to stop it when the user hides the video, just add this to the exit-script:

$(“iframe”).each(function() { $(this)[0].contentWindow.postMessage(‘{“event”:”command”,”func”:”pauseVideo”,”args”:””}’, ‘*’); });

If you want to send a play event, replace “pauseVideo” with “playVideo”, but generally you won’t do this, I think.

This example here is kind of bad, because it covers all iframes, but you can play with the jQuery selector there to make it fit your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.