0
votes

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!

1

1 Answers

0
votes

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/