I have set up a demo of parent listening for events on children. I dont understand why the following examle works with click event and not with mouseenter?
const on = (element, type, selector, handler) => {
element.addEventListener(type, (event) => {
if (event.target.closest(selector)) {
handler(event);
}
});
};
var a = document.querySelector('.a')
;
on(a, 'click', '.b', (event) => console.log('click'));
on(a, 'mouseenter', '.b', (event) => console.log('mouseenter'))
<div >
<div >this is b</div>
</div>
CodePudding user response:
From MDN:
Though similar to mouseover, mouseenter differs in that it doesn't bubble and it isn't sent to any descendants when the pointer is moved from one of its descendants' physical space to its own physical space.
Event delegation depends on the event bubbling from the element that triggered the event to the element where the event handler is bound.
Consider using mouseover
instead.
CodePudding user response:
You could try this
const on = (element, type, selector, handler) => {
document.querySelector(selector).addEventListener(type, function() {
if (this.closest(element)) {
handler(event);
}
});
};
var a = '.a';
var b = '.b';
on(a, 'click', b, (event) => console.log('click'));
on(a, 'mouseenter', b, (event) => console.log('mouseenter'))