Sylar Sylar - 4 months ago 23
HTML Question

Close dialog after 5 seconds with jquery

I'm implementing an add wishlist function to my rails app. So far I can dialog the message and get it to fade after 5 seconds. The issue is, once faded out and the user clicks on another "add wishlist" no dialog. They have to refresh the page. Im still learning so I know what's going on. I need to close the dialog with js but how?

Coming from my last question:

HTML

<section data-id="notification"></section>


JavaScript

...

// Calling the notification();
// You need to reduce that data string!
notification("<div id='noti' class='alert alert-success'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><p>WishList Added!</p></div>");

...

function notification(data){
$( "[data-id=notification]" ).append( data ).delay(5000).fadeOut(400); // I've tried adding .dialog('close')
$('#noti').dialog('close'); // this gives an error.
}

...


To conclude, when user adds to wishlist, an dialog will show. User can manually close the dialog or it will close itself after
x
seconds. If dialog closes it self and user clicks another add wishlist, alert re-appears etc. Some how I need to remove it from the dom.

Maybe it wont make sense to display a message every time the user adds/removes a wishlist but this will be useful for other parts of my app.

This question is 4 years ago. Has anything changed since? I need both: user close and js close.

Answer

You should use alert('close') :

$( "[data-id=notification]" ).append( data ).delay(5000).fadeOut(400);
$('#noti').alert('close');

Or using setTimeout :

$( "[data-id=notification]" ).append( data );
setTimeout(function() { $('#noti').alert('close'); }, 5000);

Hope this helps.

Comments