views:

221

answers:

1

I want to watch for the nodeValue change of an element that's edited with contenteditable. Basically, I want to run a function on change of the nodevalue.

I found this post: http://james.padolsey.com/javascript/monitoring-dom-properties/

Which seems to have a plugin for what I want.

Here's the watch plugin:

jQuery.fn.watch = function( id, fn ) {

    return this.each(function(){

        var self = this;

        var oldVal = self[id];
        $(self).data(
            'watch_timer',
            setInterval(function(){
                if (self[id] !== oldVal) {
                    fn.call(self, id, oldVal, self[id]);
                    oldVal = self[id];
                }
            }, 100)
        );

    });

    return self;
};

As an example, I can watch an input's value like this:

  $('#input').watch('value', function(propName, oldVal, newVal){
    $("#text").text(newVal);
  });

But not a contenteditable's nodevalue (its text content):

  $('#ce').watch('nodeValue', function(propName, oldVal, newVal){
    $("#text").text(newVal);
  });

Here's the live example:

http://jsbin.com/iconi/edit

Anyone know how to adapt the watch method to work with nodevalue. Thanks!

A: 

Isn't this simpler?

 $('#ce')
    .bind('change keyup',
       function() {
          $('#text')
             .text($(this).text());
       }
    );

As for the input:

 $('#input')
    .bind('change keyup',
       function() {
          $('#text')
             .text($(this).val());
       }
    );
Alex Bagnolini
Thanks for your suggestion. The problem is changed, there is no change event for div elements. This means that copied and pasted text won't be saved.
Jourkey