2

I have an html iframe that contains just an embeded youtube video. I'm trying to perform an action when the user clicks the video/iframe but does not work. Here is code:

html:

<iframe id="myVideo" autoplay="true" src="https://www.youtube.com/embed/pyvGEnmv1E0"></iframe>

jQuery:

$(function(){
  //line in question:
  $('#myVideo').contents().find("body").click(function(){
    //perform action here
  });
});

On the "line in question" above, I have also tried the more simple-

$('#myVideo').click(function(){});

but that fails also. Any help is wonderfully appreciated.

Andrew

user2744032
  • 317
  • 3
  • 9

1 Answers1

3

If you don't need click events to get through to the iFrame, you could use an overlay, and capture the click event on that.

Like this:

HTML:

<div id="myVideoWrapper">
    <iframe id="myVideo" autoplay="true" src="https://www.youtube.com/embed/pyvGEnmv1E0"></iframe>
    <div id="myVideoOverlay"></div>
</div>

CSS:

#myVideoWrapper {
    position:relative;
}

#myVideoOverlay {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}

JS:

$(function(){
    $('#myVideoOverlay').click(function(){
        alert('clicked');
    });
});
David
  • 371
  • 2
  • 5
  • Hi David, thanks for your quick answer, unfortunately that did not solve the problem at all. The full code of your solution is here: www.samedaygrocerydelivery.net/test2.txt and implemented here: www.samedaygrocerydelivery.net/test2.php – user2744032 Aug 30 '17 at 18:18
  • You need to add the CSS as well - that will make the overlay div element sit on top of the iframe element. Then you should see the click event fired. But like I said, it will block click events going through to iframe, so it is probably not a good solution for you. There is a trick described on the following link which may be better for you: https://stackoverflow.com/questions/2381336/detect-click-into-iframe-using-javascript#answer-23231136 – David Aug 31 '17 at 21:25
  • yeah that link you provided above worked for me. Thanks David. -Andrew – user2744032 Sep 03 '17 at 00:11