简体   繁体   中英

How to close bootstrap alert automatically in Rails?

So I have an app using bootstrap and it's alerts when you sign in, sign out etc..

I'm having trouble getting this pop up to close automatically, within 5 seconds, the class I've used to style the alert box is ".alert" and ".alert-info".

I've tried adding the following code to application.js:

window.setTimeout(function() {
    $(".alert alert-info").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);

In addition to adding it in a script tag in application.html.erb

 <script>
  window.setTimeout(function() {
    $(".alert alert-info").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);
    </script>

But it still doesn't seem to be closing automatically, what am I doing wrong?

Thanks!

The setTimeout() method will only run a single time once it is called. As is, your javascript will execute when it is loaded into the DOM, not when the popup box appears. You should add the code to the same function that shows the popup so that it is run 5 seconds after the popup is shown. Also, your jQuery selector should be $(".alert.alert-info") if you want to select an element styled with both alert and alert-info classes. You should only put your js in one place, don't repeat the same code in multiple files. It's unnecessary and will lead to unexpected behaviour. Your final code should look something like this:

setTimeout(function(){
    $(".alert.alert-info").fadeTo(500,0,function(){
        $(this).remove()
        })
    },5000)
}    

Remember to place it in your code so that it is run when the box is shown, not when the page is loaded. If you want a custom animation, check out the animate() method: http://api.jquery.com/animate/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM