Problem with jQuery mouseleave function to trigger popup

3

I'm using the mouseleave function to open a popup when the user moves the mouse out of the site.

This is the code:

jQuery('body').mouseleave(function() {
            if (!jQuery('body').hasClass('leave-on') && localStorage.getItem("leave") != "closed") {
                jQuery('body').addClass('leave-on');
            }
        });

But I have a problem with the trigger because if I click the button with the slider to slide the slider, the mouseleave is triggered and the popup appears.

The buttons that are doing mouseleave enable:

    
asked by anonymous 21.07.2018 / 04:39

1 answer

2

Actually when clicking on an element the mouseleave event is triggered. Is this a bug since the mouse did not leave the body? Or is the click event triggering the event? I did a brief search and saw comments that this would be a bug , anyway ...

To solve this, I have made this code that cancels the mouseleave event to the click and restoring it after a brief ten-second (10ms) delay. This delay is necessary because if you restore the event immediately it will be fired anyway.

But I've shifted the focus of events to document instead of body , which is more interesting because it will detect the mouse leaving the document area instead of body , which is not the same thing. The body of the page is only where the <body> tag has content, whereas document is the whole area of the window where the page is displayed, regardless of whether it has content or not.

  

I commented the lines of if so that I did not display an error in the snippet because of   of the localStorage. When copying the code, uncomment the lines.

See:

jQuery(document).ready(function(){
   var t = jQuery(this);
   t.on("click", function(){
      t.off("mouseleave");
      setTimeout(function(){
         t.on("mouseleave", function(){
            console.log("saiu"); // apenas para ilustrar, pode remover esta linha
            //if (!jQuery('body').hasClass('leave-on') && localStorage.getItem("leave") != "closed") {
               // jQuery('body').addClass('leave-on');
            //}
         });
      }, 10);
   });
   // disparo o evento para ativar o mouseleave
   t.trigger("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Aoclicarnadivabaixooeventomouseleavenãoédisparadoeoconsole.lognãoseráexibido:<divstyle="width: 50px; height: 50px; background: red;">Clique aqui</div>
    
21.07.2018 / 05:59