How to stop the event of switching between starting several times on mouseenter / mouseleave?

I am using jQuery to switch the <div> visibility using the jQuery switch method. The switch fires to the mouseenter and mouseleave events, thereby creating a div effect that folds into the mouse center and folds into the mouse trap. The problem is that if the user drags the mouse several times over the <div> and then exits the <div> , the div will turn it on and off several times. This can happen if the user accidentally moves the mouse over the <div> . Does anyone know how I can avoid this behavior?

Thanx!

+4
source share
3 answers

Two things:

  • If you intend to use both mouseenter and mouseleave , I would suggest using the hover() function; and

  • When using running animations, it’s a good habit to use the stop() method.

So:

 $("div.someclass").hover(function() { $("...").stop().fadeIn("slow"); }, function() { $("...").stop().fadeOut("slow"); }); 

Note. replace "..." with the appropriate selector for what you are switching, and use the appropriate effect (I use fade here). In addition, this in the event handler refers to the source of the event.

+7
source

You can use the more common mouseover / mouseout events to get a freeze event that doesn't fire when the mouse moves internally.

But do not use toggle in a mouse event, this can easily go wrong if, for example. the mouse is over the element while the page is loading, or the mouse leaves the browser (which may allow the mouse to leave the borders of the element without launching mouseout ). Separate the function for over , which shows the content, and out , which hides it.

Better: Use the hover() method, which is designed specifically for this purpose.

0
source

Besides the correct answer from Cletus, I would like to point out that using mouseenter and mouseleave events is not an error. The trick is only in the stop() method, in fact we can still do:

 $("div.someclass").on("mouseenter", function() { $("...").stop().fadeIn("slow"); }); $("div.someclass").on("mouseleave", function() { $("...").stop().fadeOut("slow"); }); 

Here is jsFiddle example :)

0
source

Source: https://habr.com/ru/post/1306452/


All Articles