Home > Enterprise >  Mouseleave link, reset timer and do not open popup - Elementor Popup
Mouseleave link, reset timer and do not open popup - Elementor Popup

Time:12-22

On a webpage is a link. When you hover over the link with the mouse, it displays a popup of another webpage after a time delay. Is there a way to stop the popup from opening and reset the timeout if the mouseover the link is moved off of the link before the popup opens?

Below is the code I've tried but doesnt work

<script>
  document.addEventListener('DOMContentLoaded', function() {
      let elements = document.querySelectorAll( '.districtmarketgg' );
      let popupposts = ['3525'];
  
      elements.forEach(function(e,i){
        e.addEventListener( 'mouseenter', function(){
          setTimeout(function() {
            elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
          }, 2000);
      elements.forEach(function(e,i){
        e.addEventListener( 'mouseleave', function(){
          clearTimeout(function() {
            elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
          });
        })  
      });
    });
  </script>

Thanks for your help.

I expected for the code to work but it didnt after I added the mouseleave lines of code. I've tried to add a clearTimeout function on mouseleave to the code but the code stops working after I add those lines.

CodePudding user response:

clearTimeout() takes a reference to the timer's ID that you want to clear, not a function to execute.

You also don't need to loop over the collection twice. You can set both event handlers within one loop.

If you place the following script just prior to the closing body tag, you won't need the DOMContentLoaded event handler at all.

See comments inline below:

<body>
  <!-- all page HTML here -->
<script>
  let elements = document.querySelectorAll( '.districtmarketgg' );
  let popupposts = ['3525'];
  
  // Only 1 loop is needed here
  elements.forEach(function(e,i){
    let timer = null; // Need a variable to hold a reference to the timer
  
    e.addEventListener( 'mouseenter', function(){
      // Create the timer reference
      timer = setTimeout(function() {
        elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
      }, 2000);
    });
    
    // Same loop, new event handler
    e.addEventListener( 'mouseleave', function(){
      clearTimeout(timer);  // Stop the timer
    });
  })  
</script>
</body>
  • Related