dbr
dbr

Reputation: 21

Jquery and binding an event to an iframe

**I'm currently using a jquery textselect plugin to fire alerts based on the selection text anywhere on the page and it works just fine doing something like:

$(document).ready(function() {
    $(document).bind('textselect', function(e) {
        alert(e.text); 
    });
});

I've since had to add an iframe to the page and I need the text selection to work on text within the iframe as well. I'm trying to do something like this but it's not working:

$(document).ready(function() {
    $('#iframeId').load(function() {
    $(document.getElementById("iframeId").contentWindow).bind('textselect',function(e) {
    alert(e.text); 
    });
});

At this point I've tried a whole mess of ways to reference the iframe document without any success. Any ideas?**

Upvotes: 2

Views: 5810

Answers (2)

dbr
dbr

Reputation: 1

Here's what I ended up doing just for reference... What you sent worked. The original function is passing in a document object. For an iframe document object I did something like:

window.frames["ifFrameName"].document

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630389

You can access it like this:

$(document).ready(function() {
  $('#iframeId').load(function() {
    alert("Loaded");
    $('#iframeId').contents().find("body").bind('textselect', function(e) {
      alert(e.text);
    });
  });
});

Note: This only works if the iframe is loading something on the same domain, otherwise you're going to be blocked by the same origin policy.

Upvotes: 5

Related Questions