Fixing overlapping of show().fadeout() animation. Also by using .stop() the animation does not reset itself

47 Views Asked by At

Also by using stop() the JQuery animation with show().fadeout() does not make the "reset" and overlaps the previous making a one-flow animation.

I'm going completely mad over this.

Here the code that breaks my mind

<script>
$(document).on('mouseenter','#a', function(e){
    console.log('in');
    msg('In');
});
$(document).on('mouseleave','#a', function(e){
    console.log('out');
    msg('Out');
});

function msg(str, delayMs=1500, speed='slow'){
    $("#msg").html(str);
    $("#msg").stop().show().delay(delayMs).fadeOut(speed);
}
</script>
<center>
<div id="a">EVENT</div>
<div id="msg"></div>
</center>

with a little fiddle added here

How to fix it?

How to get a result that stops the previous animation 'instantly' like if there was .hide() and makes working the .show().delay(delayMs).fadeOut(speed) correctly?

1

There are 1 best solutions below

2
user20417316 On

OOOOK. After writing with @Don't Panic in comments you can use .stop(true, true) https://api.jquery.com/stop/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).on('mouseenter','#a', function(e){
    console.log('in');
    msg('In');
});
$(document).on('mouseleave','#a', function(e){
    console.log('out');
    msg('Out');
});

function msg(str, delayMs=1500, speed='slow'){
    $("#msg").html(str);
    $("#msg").stop(true,true).show().delay(delayMs).fadeOut(speed);
}
</script>
<center>
<div id="a">EVENT</div>
<div id="msg"></div>
</center>

Tnx all <3


Edit.

mumbling...

But, if you use the click event it does not work good the same

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).on('click','#a', function(e){
    console.log('CLICKED');
    msg('CLICKED');
});
function msg(str, delayMs=1500, speed='slow'){
    $("#msg").html(str);
    $("#msg").stop(true,true).show().delay(delayMs).fadeOut(speed);
}
</script>
<center>
<div id="a" style="cursor: pointer;">EVENT</div>
<div id="msg"></div>
</center>