Site Wide Announcement in Rails using jQuery

Add to application layout file:

<div id="announcement"> Download the <a href='https://www.rubyplus.com'>Top 10 Mistakes Rails Developers</a> Make Now!</div>

Add the jQuery to hide the announcement after 5 seconds:

$('#announcement').delay(5000).fadeOut('slow');

The layout file now looks like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Anc</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>
    <div id="announcement"> Download the <a href='https://www.rubyplus.com'>Top 10 Mistakes Rails Developers</a> Make Now!</div>
    <%= yield %>
    <script type='text/javascript'>
       $('#announcement').delay(5000).fadeOut('slow');
    </script>
  </body>
</html>

For Twitter Bootstrap 4, you can use this:

<div class="alert alert-info" id='announcement'>
   Subscribe to the free <a href='https://itunes.apple.com/us/podcast/rails-screencast/id1142573687'>Rails Screencasts </a> Now!
</div>

Start the server and go to: http://localhost:3000/welcome/index to see the announcement. It will disappear after 5 seconds.

If you get:

$ is not defined

error in the javascript console of the developer tool, change the javascript in the layout like this:

  <script type='text/javascript'>
    jQuery(document).ready(function($) {
      $('#announcement').delay(5000).fadeOut('slow');  
    });  
  </script>


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.