160

I'm using .show to display a hidden message after a successful form submit.

How to display the message for 5 seconds then hide?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
josoroma
  • 1,887
  • 2
  • 14
  • 16

4 Answers4

389

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    Suggestion 2 worked perfectly with showing a checkmark icon and using fadeOut() instead of hide(). Great answer. – Kevin Zych Feb 06 '13 at 16:18
  • 2
    @wilsjd No you can't, `.delay()` will not work with `.hide()` the element will be shown then immediately hidden. See [this jsFiddle](http://jsfiddle.net/DelightedDoD/vbfue61f/1/) this is why Nick stated "If it's not an animation, use setTimeout() directly, like this:...." – Wesley Smith Oct 23 '15 at 16:05
  • Hmm, I wonder if that used to work two years ago. Nice find though. Thanks for keeping me honest. – wilsjd Oct 23 '15 at 18:32
  • I have also implemented this, but when I show msg twice within 5 seconds then it should hide prev and re-show, while it do not reset delay of first – alamnaryab Oct 25 '15 at 12:52
18

You can use the below effect to animate, you can change the values as per your requirements

$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow'); 
Rahul
  • 2,189
  • 7
  • 40
  • 60
  • 1
    $(...).fadeIn(...).animate(...).effect is not a function in JQuery 2.1.3 – entitycs Mar 14 '18 at 17:35
  • @DustinCharles Add jQueryUI not just jQuery. jQuery doesn't contain the effect() function e.g. https://code.jquery.com/ui/1.12.0/jquery-ui.min.js – Rahul Aug 12 '19 at 15:01
7

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");
Antonio Ooi
  • 1,601
  • 1
  • 18
  • 32
0

To show error message of 5 sec using ajax that is save in session in laravel 8

<div id="error">
    @php
        $error = Session::get('message');
        echo $error;
    @endphp
</div>
<script>
    $("#error").show();
    setTimeout(function() {
        $("#error").hide();
    }, 5000);
</script>