Skip to content Skip to sidebar Skip to footer

How To Stop All Events One Html Element Can Listen To?

Assume that there is div block, inside that block are many elements and they will fire many events. I don't want those events continuing bubble up, or listeners outside the div blo

Solution 1:

You must listen to every events individually and stop their propagation using e.stopPropagation(), where e is the event object. There's no way to listen to every events at once and unless you have a very specific subset of events, I wouldn't take this approach.

The most common way to handle bubbling events correctly is to validate the target element (e.target) and ignore accordingly.

For exemple, you could check if e.target === e.currentTarget to know if the event came from a child or not.

var logEl = document.getElementById('log');

document.getElementById('parent').addEventListener('click', function (e) {
    log('event comes from child? ' + (e.target !== e.currentTarget));
});

functionlog(msg) {
    logEl.appendChild(document.createElement('br'));
    logEl.appendChild(document.createTextNode(msg));
}
#parent, #parent > div {
    padding: 20px;
    border: 1px solid red;
}

#parent {
    height: 100px;
    width: 200px;
}
Click inside the boxes

<divid="parent">
    parent
    <div>child</div></div><divid="log"></div>

Post a Comment for "How To Stop All Events One Html Element Can Listen To?"