Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Event : Detect changes to the html/text of a div

I have a div which has its content changing all the time , be it ajax requests, jquery functions, blur etc etc.

Is there a way I can detect any changes on my div at any point in time ?

I dont want to use any intervals or default value checked.

Something like this would do

$('mydiv').contentchanged() {  alert('changed') } 
like image 393
BoqBoq Avatar asked Mar 27 '13 11:03

BoqBoq


People also ask

How to detect content change in div jQuery?

The changes to the html/text of a div can be detected using jQuery on() method. The on() is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.

How to detect changes in jQuery?

The change() is an inbuilt method in jQuery that is used to detect the change in value of input fields. This method works only on the “<input>, <textarea> and <select>” elements. Parameter: It accepts an optional parameter “function”. Return Value: It returns the element with the modification.


2 Answers

If you don't want use timer and check innerHTML you can try this event

$('mydiv').on('DOMSubtreeModified', function(){   console.log('changed'); }); 

More details and browser support datas are Here.

like image 171
iman Avatar answered Sep 20 '22 00:09

iman


Using Javascript MutationObserver:

// Select the target node. var target = document.querySelector('mydiv')  // Create an observer instance. var observer = new MutationObserver(function(mutations) {     console.log(target.innerText);    });  // Pass in the target node, as well as the observer options. observer.observe(target, {     attributes:    true,     childList:     true,     characterData: true }); 

See the MDN documentation for details; this should work in pretty much all current browser, including IE11.

like image 25
PPB Avatar answered Sep 20 '22 00:09

PPB