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?
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.
jQuery Effect fadeOut() Method The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect).
jQuery | Effect fadeOut() Method The fadeOut()Method in jQuery is used to change the level of opacity for selected element from visible to hidden.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With