If a user clicks on an image I want that to simultaneously trigger a click on a specified iFrame as well. Is that possible? The image and iFrame are located on the same page. If so, can you please show me the code that would work?
Here's what I have so far:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<img id="image" src="https://www.google.com/images/srpr/logo4w.png">
<iframe id="iframe" src="http://www.test.com" height= "100" width="160"></iframe>
<script>
jQuery("input.image").click(function(){
$("#iframe").click()
});
</script>
</body>
</html>
Answer: Use the jQuery contents() method If you try to detect or capture a click event inside an iframe simply using jQuery click() method it will not work, because iframe embed a web page within another web page. However, you can still do it on the same domain utilizing the jQuery contents() and load() method.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
you can always detect the click on a div using the onclick event without caring what is inside the div . but you can check if the div innerHTML to see if the ad is loaded or it's empty and if the ad was loaded then run your script.
Your jquery image selector is wrong.
change
jQuery("input.image")
to
$("#image")
Then everything will work. You can see it in this fiddle
Post Edit
If the question is to trigger a click on one of the elements contained in the iFrame, then replace the
$("#iframe").click()
with something like:
$("#iframe").contents().find("a:first").click();
This will only work if the contents of the main page and the iFrame's page are on the same domain. Otherwise browsers will prevent the action as it is cross site scripting. You can see in your example, XSS prevention will occur as demonstrated in this fiddle
I think you needed something like this:-
$("#image").click(function(){
var $iframe = $("#iframe").contents();
$("body", $iframe).trigger("click");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With