Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an alert in jQuery for a few seconds then fade it out

When an AJAX call completes, I'd like to display a message to the user that shows for 3 seconds - and then fades out. Also, I want this message to show up right before the button he pressed - #btnSubmit.

Here's my code (it doesn't work - fades out the button instead of the message):

if(response == 'success') {
   $('#btnSubmit').before('<div>Success!</div>').delay(3000).fadeOut();
}

Any ideas on how I can fade out this dynamically generated element in jQuery?

like image 506
FloatingRock Avatar asked Feb 04 '14 15:02

FloatingRock


People also ask

How do you fade text in jQuery?

The jQuery fadeIn() method is used to fade in a hidden element. Syntax: $(selector).fadeIn(speed,callback); The optional speed parameter specifies the duration of the effect.

Which jQuery function can you use to make an element fade until it disappears?

jQuery Effect fadeOut() Method The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect).

Which jQuery function can be used to apply a fading effect to your element and stop at one faded opacity level?

jQuery | Effect fadeOut() Method The fadeOut()Method in jQuery is used to change the level of opacity for selected element from visible to hidden.

Does JavaScript alert stop execution?

One of the nice things about the built-in JavaScript alert is that - unlike virtually anything else in JavaScript - it's synchronous. It's completely blocking, and no other code will execute until it's been dismissed.


1 Answers

Use insertBefore() instead of before()

$(function() {
    $('<div>Success</div>')
    .insertBefore('#btnSubmit')
    .delay(3000)
    .fadeOut(function() {
      $(this).remove(); 
    });
});
<button id="btnSubmit">button</button> 

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

so that the effect and delay are applied to the new injected element.

Further information about insertBefore(): http://api.jquery.com/insertBefore/

like image 129
Fabrizio Calderan Avatar answered Sep 20 '22 08:09

Fabrizio Calderan