How to stop bubbling on a DOMSubtreeModified Event?

I have a pretty simple script. I have the following HTML:

<h1>Hello</h1> <input type="button" value="Change" id="change" /> 

With appropriate JS:

 var h1 = $("h1").get(0); h1.addEventListener("DOMSubtreeModified", function(ev) { console.log("Changed"); ev.bubbles = false; ev.cancelBubble = true; ev.defaultPrevented = true; ev.preventDefault(); ev.stopPropagation(); ev.returnValue = false; return false; }, false); $("#change").click(function() { $("h1").text("World"); }); 

So, it basically just changes the text of the H1 node, and then the event fires. However, the event fires twice (as I believe, as a result of the bubble). As you can see, I tried to drop everything to try to make him not shoot twice, but that does not stop him. If you want to play with the code, you can check it out: http://jsfiddle.net/sECtq/ . Any help would be greatly appreciated. Thanks.

+4
source share
2 answers

This behavior is not caused by bubbles.

$. text () takes 2 steps to set new text:

  • delete existing content
  • insert new textNode

Both steps start DOMSubtreeModified, so you get 2 warnings.

You can use for example. following:

 $("h1")[0].firstChild.data="World"; 

This will change the contents of the text field without deleting the node.

+7
source

or you can also check if distribution has stopped or not. Take a look at http://api.jquery.com/event.isPropagationStopped l

0
source

All Articles