Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to add 'live' Event listener for mouseenter event type with pure JS

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...