0

I am looking for a way to pause fade out process, if user mouseover the alert to read a lengthy message..

window.setTimeout(function() {
    $(".alert").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert").slideUp(500);
    $(this).remove();
    });
}, 4000);


<div id="alert-auto-close" class="alert alert-success alert-dismissible fade show">You have been successfully logged out!
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>

any idea how this can be accomplished?

Ozzie Ghani
  • 193
  • 2
  • 13
  • Possible duplicate of [Fade in/out and pause on mouse over with jQuery](https://stackoverflow.com/questions/5806957/fade-in-out-and-pause-on-mouse-over-with-jquery) – Salvatore Jul 26 '18 at 19:23

1 Answers1

0

It's a little sloppy, but from this code you can good a start on how to format this better:

var alertBox = $('#alert-auto-close');
var slideOut = function(){
  alertBox.slideUp(500).animate({
    'opacity': 0
  }, {
    'duration': 2000,
    'queue': false,
    'complete': function(){
      $(this).remove();
    }
  });
};
var overAlert = false;
var t = null;

alertBox.on('mouseover', function(){
  $(this).stop(true);
  overAlert = true;
}).find('.close').on('click', function(){
  overAlert = false;
  alertBox.off('mouseover mouseleave');
  slideOut();
});

t = window.setTimeout(function(){
  if(!overAlert) {
    slideOut();
  }
  alertBox.on('mouseleave', slideOut);
}, 4000);

First, you want the alert stored in it's own variable for attaching events and catching the mouse over, then make the slideOut() function using the animation method for more control with the queue and complete, you want a pseudo global to keep track of the mouse with overAlert, and finally the t variable is for holding the setTimeout so we can clear it.

Now, there are much better ways to handle this as far as locating the pointer and determining of it's currently within the bounds of the alert but unless the element is going to shift or it's layered with other overlays or what have you, this should handle it in most cases (well, like 60/40).

Within the setTimeout, check to see if the flag is thrown and if not then begin the animation. Now normally this would break the default close functionality but when we attached the mouseover event you'll noticed we attached a handler for the Close button as well to make sure everything clears up and the animation is the same if the time runs out or the Close button is pressed.

And here is some documentation to go over in order to help you understand the reasons I wrote this and maybe inspire you to tweak it more (again, it could use improvement):

jQuery slideUp
jQuery animate
jQuery stop
jQuery fadeTo (the second param is the opacity, >= 0 && <= 1)
mouseenter() vs mouseover()

And a jsFiddle just because

faino
  • 3,194
  • 15
  • 17