2

**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?**

dbr
  • 21
  • 1
  • 2

2 Answers2

5

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • That doesn't seem to work. This is the plugin being used. http://plugins.jquery.com/project/textselect – dbr Mar 26 '10 at 21:28
  • @dbr - Updated the answer with a different approach, but I've rarely used custom events in a frame, not sure how it will behave. – Nick Craver Mar 26 '10 at 21:54
  • This actually does launch the alert on text select of iframe content. However, in order for it to work, the selected text has to be on the parent page. Selecting text on the iframe doesn't do anything unless text is ALREADY pre-selected on the parent page. e.text is bringing back the parent selection and not the iframe selection. Is there a way to focus the event "e" to the iframe rather than the parent? – dbr Mar 28 '10 at 16:22
0

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
Harry
  • 87,580
  • 25
  • 202
  • 214
dbr
  • 1