Home > database >  addEventListener on hover but only trigger once?
addEventListener on hover but only trigger once?

Time:10-07

I have some code that shows a popup when hovering over the .acfef-submit-button element. However, I only want this to happen once. How can I adjust this code to only allow the popup to appear once?

document.addEventListener('DOMContentLoaded', function() {
    let elements = document.querySelectorAll( '.acfef-submit-button' );
    let popupposts = ['6033'];

    elements.forEach(function(e,i){
    e.addEventListener( 'mouseenter', function(){
        elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
    } );
    });
});

CodePudding user response:

It's a little hacky but setting a viewed boolean would work.

document.addEventListener('DOMContentLoaded', function () {
    let elements = document.querySelectorAll('.acfef-submit-button');
    let popupposts = ['6033'];
    let viewed = false; // or set this in the first loop if you need to

    elements.forEach(function (e, i) {
        e.addEventListener('mouseenter', function () {
            if (viewed === false) {
                elementorProFrontend.modules.popup.showPopup({ id: popupposts[i] });
                viewed = true;
            }
        });
    });
});

CodePudding user response:

After the function, add an option object with {once: true}

CodePudding user response:

Use {once: true} so that function run only once :

document.addEventListener('DOMContentLoaded', function() {
    let elements = document.querySelectorAll( '.acfef-submit-button' );
    let popupposts = ['6033'];

    elements.forEach(function(e,i){
    e.addEventListener( 'mouseenter', function(){
        elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
    } );
    });
}, {once: true});
  • Related