2

I'm learning Rails and I'm working with a Rails web app. It has an "Order" button, and when I click it, it says: "Thank you for ordering". It's done using the flash action. I would like the message to fade away after 5 seconds. I added this code:

$(document).ready(function() {
    $("#notice").fadeOut("slow");
});

This script is inside the views/layout folder and is linked to the application.html.erb file inside the same folder. However, it is not working. What am I doing wrong and how can I fix it?

M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
ytk
  • 2,787
  • 4
  • 27
  • 42
  • 2
    http://stackoverflow.com/questions/15686598/jquery-delay-before-fadeout – AmmarCSE Jun 03 '15 at 19:39
  • what is not working, fading out after 5 seconds? – AmmarCSE Jun 03 '15 at 19:39
  • 2
    The fadeOut event should be triggered only after the message shows up. With your code, the browser just tries to fade out the #notice element as soon as the page is loaded. Besides, the way it is, it would fade the element immediately, with no delay. – lucasnadalutti Jun 03 '15 at 19:42

1 Answers1

4

Well you have to do couple things to make it happens. Here is what I would do.

  1. Add a div with an id and hide it.

    <div id="notice" style="display: none"> Thank you for your ordering </div>

  2. Add script.

    $(document).ready(function note() {
        $("#notice").fadeIn().delay(5000).fadeOut();
    });
    
  3. Add onclick function to .erb file.

    <%= link_to "Order", order_path, :onclick=>'function note()' %>

Hopefully it will help.

P.S. You also can skip step 2 and add the script directly into the .erb file.

<%=
  link_to "Order", order_path, :onclick=>'$("#notice").fadeIn().delay(5000).fadeOut();'
%>
Misha
  • 1,876
  • 2
  • 17
  • 24