6

i need to known event of content change my div element, how can i do it with jquery?

<div id="mydiv">text before</div>

after some time

<div id="mydiv>other content</div>

i do such way

$("#mydiv").change(function() { alert('yes'); });

by doesn't work

    (function(){

            var interval;

        jQuery.event.special.contentchange = {
            setup: function(data, namespaces) {
                    var $this = $(this);
                var $originalContent = $this.text();
                interval = setInterval(function(){
                    if($originalContent != $this.text()) {
                            console.log('content changed');
                            $originalContent = $this.text();
                            jQuery.event.special.contentchange.handler();
                    }
                },500);
            },
            teardown: function(namespaces){
                clearInterval(interval);
            },
            handler: function(namespaces) {
                jQuery.event.handle.apply(this, arguments)
            }
        };

    })();

$("#mydiv").bind("contentchange", function() {
   alert('yes'); ///no alert! why?
});

but i see logs in console!

vinnitu
  • 4,234
  • 10
  • 41
  • 59
  • 2
    I don't think there is a cross-browser event for this. When does the div's content change? Any chance of hooking into that function call? – Pekka Dec 26 '10 at 18:42
  • 1
    Check this post on SO. Its on similar lines of what you are asking: http://stackoverflow.com/questions/1449666/create-a-jquery-special-event-for-content-changed – Chandu Dec 26 '10 at 18:46
  • How specifically are you changing the content of the element? – Šime Vidas Dec 26 '10 at 18:48
  • 1
    content change not me - my code is inject from chrome extension – vinnitu Dec 26 '10 at 19:35

2 Answers2

12

You could trigger a custom event after you change the content of the element:

var $mydiv = $("#mydiv"); 

// set up the custom event handler
$mydiv.bind("contentchange", function() {
    alert("changed");
});

// change the content and trigger a custom event
$mydiv.html("other content").trigger("contentchange");

// and again
$mydiv.html("yet other content").trigger("contentchange");
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • @vinnitu So the Chrome extension is changing the content of the element? In that case, my solution won't cut it. Check out the answer to this question: stackoverflow.com/questions/1449666/ – Šime Vidas Dec 26 '10 at 19:43
1
"The change event is sent to an element when its value changes. 

This event is limited to <input> elements, <textarea> boxes and <select> elements. "

You cannot use the change event on divs.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93