Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an Event Listener to Items in an iFrame?

Given an iframe with <span class="fineme"> throughout the iframe...

Is it possible to add an event listener with jQuery to trigger an ALERT anytime the user moves their mouse over .fineme in the iframe, from the top/parent window?

like image 393
AnApprentice Avatar asked Jul 18 '10 00:07

AnApprentice


2 Answers

See http://api.jquery.com/contents/ for accessing content document of an iframe.

A solution to your question might be:

$("iframe#name").contents().find(".fineme").bind("mouseover", function() { alert("Found me"); });
like image 143
Sean Hogan Avatar answered Sep 23 '22 01:09

Sean Hogan


Yea, It seems that by default if you run a selector from the parent window it won't find elements inside the iframe. However, you can explicitly give jQuery the context in order to look inside the iframe.

One way to do this would be:

var iframe = $("#someIframeId");
$(".fineme",iframe.get(0).contentDocument).mouseover(function(){alert('hi')});

NOTE: This will only work if both the parent site and the IFrame are on the same domain. For more information about this see: http://madskristensen.net/post/Iframe-cross-domain-JavaScript-calls.aspx

like image 41
Matthew Manela Avatar answered Sep 25 '22 01:09

Matthew Manela