jQuery show for 5 seconds then hide
Asked Answered
O

4

162

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

How to display the message for 5 seconds then hide?

Oconnor answered 7/8, 2010 at 1:20 Comment(0)
H
393

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();
});
Hezekiah answered 7/8, 2010 at 1:22 Comment(4)
Suggestion 2 worked perfectly with showing a checkmark icon and using fadeOut() instead of hide(). Great answer.Suburb
@wilsjd No you can't, .delay() will not work with .hide() the element will be shown then immediately hidden. See this jsFiddle this is why Nick stated "If it's not an animation, use setTimeout() directly, like this:...."Bethanybethe
Hmm, I wonder if that used to work two years ago. Nice find though. Thanks for keeping me honest.Philosopher
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 firstYurt
Z
19

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'); 
Zook answered 9/1, 2012 at 11:59 Comment(2)
$(...).fadeIn(...).animate(...).effect is not a function in JQuery 2.1.3Remorseless
@DustinCharles Add jQueryUI not just jQuery. jQuery doesn't contain the effect() function e.g. code.jquery.com/ui/1.12.0/jquery-ui.min.jsZook
A
7

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");
Anders answered 26/6, 2020 at 10:8 Comment(0)
T
1

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>
Treaty answered 23/4, 2022 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.