Hello. In order.
1) Strange string:
if ($('.response').fadeIn()) $('.response').delay(1000).fadeOut();
$('.response').fadeIn() returns the same as $('.response') , i.e. A jQuery object that, inside the if (){} condition, is transformed to true . And then the use of the if (){} construct is absolutely unnecessary. If you remove it:
$('.response').fadeIn(); $('.response').delay(1000).fadeOut();
then nothing will change.
2) As written above, $('.response').fadeIn() returns the same jQuery object. Thus, the object can be addressed only once, and then apply all the necessary methods along the chain:
$('.response').text('Success').fadeIn().delay(1000).fadeOut();
This will not only reduce the code, but also make it more productive, because In this case, the search for an element in the document tree is performed only once.
3) For question:
How to make the animation cancel when you hover over the .response block, and as soon as the mouse outside the borders. .response .fadeOut() worked?
I rewrote your code, the working version looks like this:
var timeout; $('.button').on('click', function() { $('.response').text('Success').fadeIn(); timeout = setTimeout(function(){ $('.response').fadeOut(); }, 1000); }); $('.response').on({ mouseenter: function(){ clearTimeout(timeout); }, mouseleave: function(){ $('.response').stop().fadeOut(); } });
See the work here: https://jsfiddle.net/rf6pkd7f/
What happens there:
- As it was, on click we put the text "Success" and show it through
.fadeIn() ; - Instead of
.delay() use setTimeout() to be able to cancel .fadeOut() when the cursor is on the .response block; - The
setTimeout() function returns a timer identifier that can be used to cancel a timer and an action that is tied to it. This identifier is written in the previously created global variable timeout ; - Using the
.on() method, .on() hang two handlers on .response - for the mouseenter and mouseleave ; - With
mouseenter (i.e. hover), we cancel the timer with the clearTimeout function so that the block does not disappear. - With
mouseleave (i.e., the cursor leaves the element), stop the animation (if fadeIn() has not yet completed) with the .stop() method, then hide the block with .fadeOut() .
I strongly recommend reading the jQuery tutorial on the official website if you speak English - https://learn.jquery.com/about-jquery/ , or something similar in Russian. After that, these questions you will be much less.