xSketchy0 xSketchy0 - 3 months ago 9
Javascript Question

Don't trigger the Jquery event after a button has been pressed

So I've been trying to make this event where if you hover with your mouse near the back button, this div will show up a message saying "Where are you going? :(". I've got it working, but after some time, it becomes annoying.

HTML:

<div class="leaveModal dontgo">
<h1>Where are you going? :(</h1>
<div class="closebutton">
<i class="fa fa-times fa-lg" aria-hidden="true"></i>
</div>
</div>


JavaScript:

$("body").on("mousemove",function(event){
if (event.pageX < 100 && event.pageY < 50) {
$(".dontgo").fadeIn(600);
}
}

/* Close Button */

$(".fa-times").click(function(){
$(".dontgo").fadeOut(500);
})


Whenever I press the close button it closes, but it'll keep triggering the event. When I move towards my back button it becomes quite annoying for people.

Does anyone know how to make it not trigger the jQuery event after pressing the close button once?

Answer

What about turning off the body listener when the button is clicked?

$(".fa-times").click(function(){
    $("body").off("mousemove");  //Turn off the listener for body
    $(".dontgo").fadeOut(500);
})

EDIT: As war10ck mentioned in the comments on this answer, the $("body").off(); portion of the snippet above will remove all events bound to your body. I've edited my answer to instead say $("body").off("mousemove");, which will remove only the mousemove event.

Comments