Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a video with jQuery located inside an iFrame

I have an iFrame on a page set to display: none;

<div id="the-stage" style="display:none;">
<iframe src="index.html" scrolling="no">
</iframe>
</div><!--end the-stage-->

Which has a <video> tag within it:

<video id="video1" width="345" height="264" controls poster="poster.jpg">
<source src="video.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
<source src="video.webm" type='video/webm; codecs="vp8, vorbis"'>
<source src="video.ogv" type='video/ogg; codecs="theora, vorbis"'>
</video>

On the page which has the <iframe> tag, I was trying to play the video when the hidden div is revealed:

jQuery("a.launch").click(function(){
jQuery("#the-stage").fadeIn();
jQuery("#video1").get(0).play();
return false;
});

But then I got the following error in the console:

// The console output. cannot call method play of undefined

Any ideas? Thank you in advance.

like image 572
Yahreen Avatar asked Sep 04 '11 01:09

Yahreen


People also ask

Can you use jQuery in an iframe?

You can use jQuery to add jQuery effects to your iFrame elements, to change the CSS rules, or even to add content. Above, the script is used to change the background color of the . page element within the frame to white.

How can get iframe HTML using jQuery?

# jQuery Code to Get HTML Content of IFrame$("#myButton"). on('click', function() { alert($("#myIframe"). contents(). find("html").

How to pause a video in iframe?

Click either the play or pause button, which is part of the iframe's parent page, to see it initiate play/pause of the video in the iframe player.


1 Answers

You need to use contents() to get the iframe content and then find the video element. Also you should make sure to do this after the div is visible i.e when fading is complete. The reason is when the div which contains iframe is hidden the video will not play.

jQuery("a.launch").click(function(){
   jQuery("#the-stage").fadeIn(function(){
       jQuery("#the-stage").find("iframe").contents().find("#video1").get(0).play();
   });
   return false;
});
like image 134
ShankarSangoli Avatar answered Oct 11 '22 08:10

ShankarSangoli