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

13

352

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')
}
Brian answered 27/3, 2013 at 11:25 Comment(2)
Possible duplicate: #10328602Rior
@Rior That's binding a keypress event to a contenteditable <div> element. I'm not sure the solutions there apply to this. They definitely wouldn't pick up any programmatic changes to the content of an element.Redingote
O
532

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.

Orsay answered 30/4, 2013 at 4:41 Comment(9)
this event is deprecated w3.org/TR/DOM-Level-3-Events/#glossary-deprecatedRunnel
Mozilla 33: falled in recursion for element <body>. Needed to find another wayRedneck
It's serious DO NOT use this event it will crash all your work cos it is fired all the time. Instead use the events below $('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() { });Hunfredo
For those looking for a non depreciated answer: Scroll downLustrum
This answer, using on() instead of bind() should be the accepted oneSulfonmethane
@IsaiyavanBabuKaran please what is your solution to to replicate the exact same code of the answer that isn't deprecated ?Busby
Mutation events handled in this manner a deprecated - try this: gabrieleromanato.name/…Neary
remember the # '#mydiv'Gringo
@Gringo this is just a sample and mydiv is not an Id. it is just like answer sample code. but thanks for mention it.Orsay
T
128

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.

Taeniafuge answered 15/3, 2017 at 9:36 Comment(5)
This is the correct answer as this is now favoured over using DOMSubtreeModifiedRosalbarosalee
I am getting error with this, even though I have given correct selector. "VM21504:819 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'."Godric
@Godric The error apppears when your selected element was not found. It could be that the element you are trying to observe does not exist when your code executes. This answer is quite usefulChronometry
I will this snippet here. HTMLElement.prototype.onDOMSubtreeModified = function(c, o = {attributes: true, childList: true, characterData: true}){return new MutationObserver((m) => {c.call(this, m);}).observe(this, o);};Skeleton
In the nested situation I found myself in I needed to add subtree: true to the observer options (as also seen in the config example of MDN documentation)Goshorn
D
76

Since $("#selector").bind() is deprecated, you should use:

$("body").on('DOMSubtreeModified', "#selector", function() {
    // code here
});
Divinity answered 15/3, 2017 at 8:57 Comment(2)
This was the differentiating factor, the additional # to indicate that the symbol must go before the selector.Ambiguity
It does work.Changin #selector for #mydiv did the trick, thanksUpu
B
47

You can try this

$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {

});

but this might not work in internet explorer, haven't tested it

Boxberry answered 10/5, 2013 at 11:40 Comment(6)
Deprected: developer.mozilla.org/en-US/docs/Web/Guide/Events/… Use instead: developer.mozilla.org/en-US/docs/Web/API/MutationObserverElectorate
NOTE!: if you use this for a trigger and there's a lot of changes being made to the page - it will run your function X times (maybe even X=1,000 or more) which could be very inefficient. One simple solution is to define a "running" boolean var, that will... if(running == true){return} ...without running your code if it's already running. Set running=true right after your if logic, and running=false before your function exits. You could also use a timer to limit your function to only be able to run every X seconds. running=true; setTimeout(function(){running=false},5000); (or something better)Firehouse
I used this on a select box that had options being added and removed. It worked great when items were added but the remove seemed to be 1 item behind. When the last option was removed it wouldn't fire.Flinders
@Firehouse You can also bump the timeout timer by clearing & setting timeout again: clearTimeout(window.something); window.something = setTimeout(...);Hooey
agreed - your way is the way to go - since learning Python I've cleared up a lot of my poor coding practices across multiple languages (not all, just a lot ;)Firehouse
@RandallFlagg please how to use MutationObserver to replicate the exact same code of the answer ?Busby
T
37

You are looking for MutationObserver or Mutation Events. Neither are supported everywhere nor are looked upon too fondly by the developer world.

If you know (and can make sure that) the div's size will change, you may be able to use the crossbrowser resize event.

Tridentine answered 27/3, 2013 at 11:51 Comment(3)
This is the one. Specifically, DOMSubtreeModified. You might find the mutation-summary library helpful, and this list of DOM Tree Events.Hyohyoid
this event is deprecated developer.mozilla.org/en-US/docs/Web/Guide/Events/…Lemal
Incase anyone else has had to try read through everything everywhere, this is the correct answer. Mutation Events were supported in past browsers, Mutation Observer is what will is supported in modern browsers and will be supported in the future. See link for support: CANIUSE Mutation ObserverLustrum
R
30

The following code works for me:

$("body").on('DOMSubtreeModified', "mydiv", function() {
    alert('changed');
});
Ravel answered 22/3, 2017 at 10:26 Comment(0)
H
17

There is no inbuilt solution to this problem, this is a problem with your design and coding pattern.

You can use publisher/subscriber pattern. For this you can use jQuery custom events or your own event mechanism.

First,

function changeHtml(selector, html) {
    var elem = $(selector);
    jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
    elem.html(html);
    jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
}

Now you can subscribe divhtmlchanging/divhtmlchanged events as follow,

$(document).bind('htmlchanging', function (e, data) {
    //your before changing html, logic goes here
});

$(document).bind('htmlchanged', function (e, data) {
    //your after changed html, logic goes here
});

Now, you have to change your div content changes through this changeHtml() function. So, you can monitor or can do necessary changes accordingly because bind callback data argument containing the information.

You have to change your div's html like this;

changeHtml('#mydiv', '<p>test content</p>');

And also, you can use this for any html element(s) except input element. Anyway you can modify this to use with any element(s).

Heliogabalus answered 24/5, 2013 at 9:26 Comment(3)
To observe and act on changes to a particular element, just modify the changeHtml function to use 'elem.trigger(...)' instead of 'jQuery.event.trigger(...)', and then bind to the element like $('#my_element_id').on('htmlchanged', function(e, data) {...}Chesser
"this is a problem with your design and coding pattern", what to do if you include third party scripts therefore you have no control on their source code? but you need to detect their changes to one div?Terrilynterrine
@Terrilynterrine a rule of thumb is to choose third party lib with callback event providedSwindell
S
11

Use MutationObserver as seen in this snippet provided by Mozilla, and adapted from this blog post

Alternatively, you can use the JQuery example seen in this link

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();
Shebeen answered 23/5, 2018 at 17:20 Comment(0)
L
5

Tried some of answers given above but those fires event twice. Here is working solution if you may need the same.

$('mydiv').one('DOMSubtreeModified', function(){
    console.log('changed');
});
Leveridge answered 28/8, 2020 at 14:24 Comment(1)
Worked in Chrome; didn't work in FFAutotruck
C
2

Try the MutationObserver:

browser support: http://caniuse.com/#feat=mutationobserver

<html>
  <!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->

  <head>
    </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
      // Inspect the array of MutationRecord objects to identify the nature of the change
function mutationObjectCallback(mutationRecordsList) {
  console.log("mutationObjectCallback invoked.");

  mutationRecordsList.forEach(function(mutationRecord) {
    console.log("Type of mutation: " + mutationRecord.type);
    if ("attributes" === mutationRecord.type) {
      console.log("Old attribute value: " + mutationRecord.oldValue);
    }
  });
}
      
// Create an observer object and assign a callback function
var observerObject = new MutationObserver(mutationObjectCallback);

      // the target to watch, this could be #yourUniqueDiv 
      // we use the body to watch for changes
var targetObject = document.body; 
      
// Register the target node to observe and specify which DOM changes to watch
      
      
observerObject.observe(targetObject, { 
  attributes: true,
  attributeFilter: ["id", "dir"],
  attributeOldValue: true,
  childList: true
});

// This will invoke the mutationObjectCallback function (but only after all script in this
// scope has run). For now, it simply queues a MutationRecord object with the change information
targetObject.appendChild(document.createElement('div'));

// Now a second MutationRecord object will be added, this time for an attribute change
targetObject.dir = 'rtl';


      </script>
    </body>
  </html>
Clepsydra answered 21/11, 2016 at 14:58 Comment(0)
F
2

DOMSubtreeModified is not a good solution. It can cause infinite loops if you decide to change the DOM inside the event handler, hence it has been disabled in a number of browsers. MutationObserver is the better answer.

MDN Doc

const onChangeElement = (qSelector, cb)=>{
 const targetNode = document.querySelector(qSelector);
 if(targetNode){
    const config = { attributes: true, childList: false, subtree: false };
    const callback = function(mutationsList, observer) {
        cb($(qSelector))
    };
    const observer = new MutationObserver(callback);
    observer.observe(targetNode, config);
 }else {
    console.error("onChangeElement: Invalid Selector")
 }
}

And you can use it like,

onChangeElement('mydiv', function(jqueryElement){
   alert('changed')
})
Fernyak answered 9/11, 2020 at 6:25 Comment(0)
O
1

You can store the old innerHTML of the div in a variable. Set an interval to check if the old content matches the current content. When this isn't true do something.

Obtrude answered 27/3, 2013 at 18:46 Comment(0)
C
0

Adding some content to a div, whether through jQuery or via de DOM-API directly, defaults to the .appendChild() function. What you can do is to override the .appendChild() function of the current object and implement an observer in it. Now having overridden our .appendChild() function, we need to borrow that function from an other object to be able to append the content. Therefor we call the .appendChild() of an other div to finally append the content. Ofcourse, this counts also for the .removeChild().

var obj = document.getElementById("mydiv");
    obj.appendChild = function(node) {
        alert("changed!");

        // call the .appendChild() function of some other div
        // and pass the current (this) to let the function affect it.
        document.createElement("div").appendChild.call(this, node);
        }
    };

Here you can find a naïf example. You can extend it by yourself I guess. http://jsfiddle.net/RKLmA/31/

By the way: this shows JavaScript complies the OpenClosed priciple. :)

Convict answered 27/3, 2013 at 11:58 Comment(2)
It does not work with append child... I actually modify the html of it via other functions.Brian
Like removeChild() replaceChild() etc. But you're right on innerHTML. You should avoid it somehow.Convict

© 2022 - 2024 — McMap. All rights reserved.