Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html element content change event

Tags:

jquery

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!

like image 480
vinnitu Avatar asked Dec 26 '10 18:12

vinnitu


People also ask

Which event is triggered when the contents of a text element is changed?

The change event is fired for <input> , <select> , and <textarea> elements when the user modifies the element's value.

What is change () in JavaScript?

The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.

What triggers Onchange event?

The onchange JavaScript event is triggered when an element is changed and then loses focus. In the context of a textarea , this happens when the content of the textarea is modified and then the textarea loses focus because the user clicks away or presses the tab key.


2 Answers

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");
like image 99
Šime Vidas Avatar answered Nov 02 '22 08:11

Šime Vidas


"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.

like image 25
Uku Loskit Avatar answered Nov 02 '22 10:11

Uku Loskit