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

javascript, jquery

Solution

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/

Problem

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?

Original source