"$(document).on" Not Triggering After Event.stoppropagation And "$(a).on" Not Triggering For New Elements
I'm trying to write a chrome extension (for casperjs testing). A part of the extension needs to bind to the click event which I'm doing like this: $(document).on('click', 'a', null
Solution 1:
Any ideas?
Event handling is separated in two phases: capturing phase and bubbling phase:
| | / \
-----------------| |--| |-----------------
| element1 | | | | |
| -------------| |--| |----------- |
| |element2 \ / | | | |
| -------------------------------- |
| W3C event model |
------------------------------------------
By default event handlers are bound to listen to the bubbling phase (event handlers bound with jQuery as well).
To react to the event before the element's own event handler is called, you have to bind the handler to the capturing phase. Note that especially older IE browsers don't support this.
Since jQuery doesn't let you do this, you have to use the DOM API directly:
document.addEventListener('click', function(event) {
// test whether event originates inside <a> first // (search on SO to find out how)// then:
handler.call(event.target, event);
}, true);
document.addEventListener('click', function(event) {
if (event.target.nodeName !== 'BUTTON') {
return;
}
console.log('Called first.');
}, true);
document.addEventListener('click', function(event) {
if (event.target.nodeName !== 'BUTTON') {
return;
}
console.log('Called last.');
});
document.querySelector('button').onclick = function(event) {
console.log('Called in between (could cancel bubbling here)');
// event.stopPropagation();
};
<button>Click me and look at the console</button>
Post a Comment for ""$(document).on" Not Triggering After Event.stoppropagation And "$(a).on" Not Triggering For New Elements"