Skip to content

Instantly share code, notes, and snippets.

@baldwindavid
Created August 5, 2011 18:23
Show Gist options
  • Save baldwindavid/1128167 to your computer and use it in GitHub Desktop.
Save baldwindavid/1128167 to your computer and use it in GitHub Desktop.
$(function() {
$(".flash").livequery(function(){
$(this).delay(5000).fadeThenSlideToggle();
});
});
<% if @item.valid? %>
jQuery("#some-element").prepend("<div class='flash notice'>Item created!</div>");
<% else %>
jQuery("#some-element").prepend("<div class='flash error'><%= escape_javascript(render('shared/error_messages', :target => @item)) %></div>");
<% end %>
@mileszs
Copy link

mileszs commented Aug 5, 2011

Nice. I like that. It's a bit cleaner than my idea, too, I think. I've got something like

$(function() {
  if ($('#flash').is('visible')) {
    $('#flash').delay(5000).slideUp(1000);
  }
});

Then later:

var update_flash = function(message) {
  $('#wrapper').prepend('<div id="flash">' + message + '</div>')
  $('#flash').slideDown(1000).delay(5000).slideUp(1000);
}

I call, in update.js or whatever

update_flash('<%= escape_javascript(flash[:notice])%>');

In coffeescript, the first part looks like:

$ ->

  if $('#flash').is('visible')
    $('#flash').delay(5000).slideUp(1000)

window.update_flash = (message) ->
  $("#wrapper").prepend('<div id="flash">' + message + '</div>')
  $("#flash").slideDown(1000).delay(5000).slideUp(1000)

@baldwindavid
Copy link
Author

Interesting to see other ways to do it. In my case, I have flash messages appearing in various areas so I don't use an id for the flash...though I might change to a single flash area. I'm wondering with your example here if since you presumably always have the div#flash available on the page that you could just replace the text in update_flash instead prepending...

var update_flash = function(message) {
  $('#flash').text(message).slideDown(1000).delay(5000).slideUp(1000);
}

Otherwise it seems like you will end up with multiple elements with the same ID.

@mileszs
Copy link

mileszs commented Aug 5, 2011 via email

@baldwindavid
Copy link
Author

Well, I probably never would have noticed, but was just recently dealing with a #flash in a single place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment