I have a pretty simple scenario. I have the following HTML:
<h1>Hello</h1>
<input type="button" value="Change" id="change" />
With the corresponding 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, this basically just changes the text of the H1 node and the event is then fired. However, the event is firing twice (as I assume as a result of bubbling). As you can see, I've tried throwing everything at it to try to get it to not fire twice, but that does not stop it. If you want to play with the code, you can check it out at: /. Any help would be appreciated.
I have a pretty simple scenario. I have the following HTML:
<h1>Hello</h1>
<input type="button" value="Change" id="change" />
With the corresponding 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, this basically just changes the text of the H1 node and the event is then fired. However, the event is firing twice (as I assume as a result of bubbling). As you can see, I've tried throwing everything at it to try to get it to not fire twice, but that does not stop it. If you want to play with the code, you can check it out at: http://jsfiddle/sECtq/. Any help would be appreciated.
Share Improve this question edited Jan 13, 2023 at 13:58 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 22, 2011 at 1:41 naivedevelopernaivedeveloper 2,9588 gold badges37 silver badges49 bronze badges 1-
ev.preventDefault();
will cause IE to throw an exception – qwertymk Commented Jul 22, 2011 at 2:24
2 Answers
Reset to default 7This behaviour is not caused by bubbling.
$.text() executes 2 steps to set the new text:
- remove the existing contents
- insert a new textNode
Both steps trigger DOMSubtreeModified, so you get 2 alerts.
You may use e.g. the following:
$("h1")[0].firstChild.data="World";
This will only change the contents of the textNode without removing a node.
or you can also check whether propagation has been stopped or not. Take a look on the http://api.jquery./event.isPropagationStopped l