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