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>