Created
December 23, 2010 00:31
-
-
Save structuralartistry/752369 to your computer and use it in GitHub Desktop.
Simple fading flash[:notice] in Rails with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I struggled with getting a fading flash[:notice] that would work both with standard served pages as well | |
# as ajax requests. I saw a number of posts online but did not have luck with or they seemed too | |
# complicated. This is what I ended up with from experimentation. | |
# Place the following code in application_helper.rb. Note that you need to either change or name your | |
# containers as I have in this code: | |
# application_helper.rb | |
module ApplicationHelper | |
def fading_flash_notice | |
# note: you must have a div with id='notices' or rename the div appended to below with your element which | |
# is the container for the flash messages | |
return '' if !flash[:notice] | |
notice_id = rand.to_s.gsub(/\./, '') | |
notice = <<-EOF | |
$('#notices').append("<div id='#{notice_id}' class='flash_notice'>#{flash[:notice]}</div>"); | |
$("##{notice_id}").fadeOut(5000); | |
EOF | |
notice.html_safe | |
end | |
end | |
# Then in the application template (application.html.erb) place this code in the head: | |
# application.html.erb | |
<% if flash[:notice] %> | |
<script language='javascript'> | |
$(document).ready(function() { | |
<%= fading_flash_notice %> | |
}); | |
</script> | |
<% end %> | |
# If you are sending ajax responses and they contain a flash[:notice], then just put this in your .js.erb file: | |
# any .js.erb ajax response | |
<%= fading_flash_notice %> | |
# If you want to add a spec to test your helper method use this: | |
# application_helper_spec.rb | |
describe ApplicationHelper do | |
it "should return a good fading flash notice" do | |
flash[:notice] = 'hello world' | |
fading_flash_notice.should =~ /<div id='.*?' class='flash_notice'>hello world<\/div>/ | |
fading_flash_notice.should =~ /\$\(".*"\).fadeOut\(.*\);/ | |
end | |
end | |
notice_id = rand.to_s.gsub(/\./, '')
such slippery ^_^'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thankyou! Thankyou! Just popped this in and it's a lovely effect. I'm going to try and float it, and put a background in, but this is just a nice bit of work, and I really appreciate you sharing it.