Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to trigger a click on an iFrame?

Tags:

jquery

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>
like image 846
user2453693 Avatar asked Jun 04 '13 22:06

user2453693


People also ask

How to click on iframe using jQuery?

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.

How do you trigger a click element?

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.

How do I find if a click event on a cross domain iframe?

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.


2 Answers

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

like image 57
dcarson Avatar answered Oct 11 '22 03:10

dcarson


I think you needed something like this:-

$("#image").click(function(){
     var $iframe = $("#iframe").contents();
     $("body", $iframe).trigger("click");
});
like image 33
pvnarula Avatar answered Oct 11 '22 01:10

pvnarula