0

I have a textarea, and using a JQuery plugin I convert it to a simple HTML editor.

The problem is that I don't know how to asign the onchange event to the html editor, since asigning the event to the textarea itself won't work.

The plugin creates an iframe and the HTML inside this iframe is the html displayed on the html editor.

I also manage to get the HTML content using:

var html = $("#txt_extradata").closest("tr").find(".sceditor-container iframe").contents().find("html").html();

Now, how can I write an event to detect if this html changes through time?

enb081
  • 3,831
  • 11
  • 43
  • 66

2 Answers2

3

You need to bind to the body of the iframe by using a contextual selector like so:

$(function() { 
     var ctx = $(".sceditor-container iframe").contents();
     $('body', ctx).blur(function() {
         //detect changes to the widget
     });
});

This will bind a keydown event to the body tag of the iframe. You may decide that keydown is not the appropriate event for your needs but regardless, this will get you to where you can simply bind the event you want.

EDIT:

Here is a jsfiddle for proof of concept http://jsfiddle.net/SJQZN/

Unfortunately, I couldn't quite get jsfiddle to properly load the css from their github repository so I made do with a quick hack up of my own.

Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
  • Selectors may need fine tuning if there are multiple of these widgets on a page. – Matthew Cox Apr 03 '13 at 07:42
  • Thanks a lot, this is very helpful, however this works only then user is using the html editor as a normal textarea, i.e. only when he is typing. For instance, if I make the text bold, the alert won't show up. – enb081 Apr 03 '13 at 08:12
  • PS. the css is loaded, but you cannot put the images of the buttons in the JSFIDDLE, anyways it was very helpful. – enb081 Apr 03 '13 at 08:13
  • I fixed it but using `blur` instead of `keydown`. :) – enb081 Apr 03 '13 at 08:46
  • Great to hear it worked. I updated the code to use the blur event. – Matthew Cox Apr 03 '13 at 14:19
1

Combining answers from here and here. You now have this

$(".sceditor-container iframe").contents().find("body")
    .on("input propertychange", function() {
        // your method.
    });
Community
  • 1
  • 1
viclim
  • 959
  • 8
  • 16