I’m trying to add a live version of event listener in pure JavaScript to monitor a mouseenter
event in order to execute specific function each time the user enters his mouse on specific element.
Here is what I have, but it’s not continuously monitoring the mouseenter
:
const selector = document.querySelector('#selectorId'); if (selector) { selector.addEventListener('mouseenter', e => { e.stopPropagation(); myFunc(); }, false); }
the goal is to keep listening to this event even after DOM update
Any thoughts?
Advertisement
Answer
Well, after some research I got to conclusion, that using a mutation observer is a way to go.
Here is a solution I’m happy with, for anyone else, who would stack to to same problem:
MutationObserver = window.MutationObserver || window.WebKitMutationObserver; const observer = new MutationObserver(function (mutations, observer) { // fired when a mutation occurs (function () { const selector = document.querySelector('#selectorId'); if (selector) { selector.addEventListener('mouseenter', e => { e.stopPropagation(); alert('bbb'); }, false); } })(); }); // define what element should be observed by the observer // and what types of mutations trigger the callback observer.observe(document, { subtree: true, attributes: true //... });
thanks to @apsillers for useful trick in the following thread: Is there a JavaScript / jQuery DOM change listener?