Reputation: 447
In my Rails application I have flash messages and I would like it so that each time there is a flash message, it scrolls down from the top (all the content goes lower) stays for a few seconds and the slides back up.
How can I do this with jQuery?
Do I toggle the height?
Sometimes the message will be injected into the HTML which means that the slideDown
won't work since the DOM has already loaded, how can I have it so jQuery looks for .message
and then applies the slideDown
and slideUp
?
Upvotes: 5
Views: 31311
Reputation: 697
You can do it like this. here duration is in milliseconds.
$.fn.flash_msg=function(duration){
this.fadeIn().delay(duration).fadeOut(function(){
this.remove();
})
}
$("#message").flash_msg(1500);
Upvotes: 0
Reputation: 27
function flashRed(sel, blinks){ //using jQuery
blinks = blinks||3
var x = $(sel),
bg = x.css('background-color'),
fg = x.css('color'),
counter = 0,
f, b;
for(var i = 0; i < blinks * 2; i++){
setTimeout(function(){
if(counter%2){
f=fg; b=bg
}
else{
f='white'; b='red'
}
counter++
x.css({'color':f, 'background-color':b})
},i*400)
}
}
Upvotes: 0
Reputation: 6346
use JQuery's slideDown()
and call slideUp()
in the callback coupled with a timer:
$("#message").slideDown(500, function(){
setTimeout(function(){
$("#message").slideUp(500);
},5000);
});
Upvotes: 0
Reputation: 532435
I'll assume your flash message is contained in some element that is (or can be) identified by class. You want to find the first one, then adjust the scroll position to the top of that element (or some offset from it), then wait and scroll back to the top.
$(function() {
var $flashMsg = $('.flash-message:first');
if ($flashMsg.length) { // we've got one
var top = $flashMsg.offset().top;
$('html,body').animate({ scrollTop: top })
.delay(3000)
.animate({ scrollTop: 0 });
}
});
Upvotes: 1
Reputation: 7041
You can make it slide down, wait for couple of seconds and slide back again with this:
$(selector for your message).slideDown(function() {
setTimeout(function() {
$(selector for your message).slideUp();
}, 5000);
});
Change the 5000
to the time you want the message to stay visible in milliseconds.
And remember to set display: none;
in CSS for your message, so that it does not appear until jQuery goes in.
Upvotes: 11