skip to Main Content

I’m using Rails 5. I want to create a message that flashes on my page after I submit an AJAX form and an error comes back. I’m not using twitter bootstrap and would only consider using that if it doesn’t screw up any of the other styling I already have. Anyway, on my view I have this

<div id="error_explanation" class="alert alert-success"></div>

and in my controller I have this

displayError('#{error_msg}')

which invokes this coffee script …

@displayError = (msg) ->
  ...

  $("#error_explanation").text(msg)

As you guess, right now, the message just displays in plain text . I would like it to flash and then disappear. How do I do that?

3

Answers


  1. Based on nothing but your coffee script, here’s how:

    Not familiar with CoffeeScript and its syntax, so here's plain JS code.

    setTimeout(function() {
    $('#visitLink').hide()
    }, 2000);

    That’ll make the message disappear after 2 seconds.

    Login or Signup to reply.
  2. If you just need the message to fade out after a set amount of time, then change that last line of CoffeeScript to:

    $("#error_explanation").text(msg).delay(3000).fadeOut()
    

    If you need something a bit more complex (e.g. don’t fade out if hovered, stacked notifications, dismiss button etc), or ready-styled – then you might want to investigate using a JS library such as toastr.

    Login or Signup to reply.
  3. this should help get you started:

    show_ajax_message = (msg, type) ->
      $("#flash-message").html "<div id='flash-#{type}'>#{msg}</div>"
      $("#flash-#{type}").delay(5000).slideUp 'slow'
    
    $(document).ajaxComplete (event, request) ->
      msg = request.getResponseHeader("X-Message")
      type = request.getResponseHeader("X-Message-Type")
      show_ajax_message msg, type
    

    https://www.google.com/search?q=flash+messages+session+rails+ajax

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search