How do I make Alert disappear after I display it in a div?

Asked

Viewed 1,492 times

0

I am making an application using Javascript and Jquery, and when I put an Alert to display an error in a div, it does not disappear, just by clicking on the x to close, I would like to know how to make it disappear after some time.

 Código HTML
 <div id="erro" class="alert alert-danger alert-dismissible fade show">
                        <button type="button" class="close" onclick="$('#erro').hide()">&times;</button>
                        IP fora da faixa, por favor, digite dois IP's válidos
 </div>


Código JavaScript
$("#erro").show();
  • Look, I find it interesting to wait for the user to click on the X, so he will be aware of the message. If he gets distracted and the message disappears on its own, he may not know what happened. Besides, if you want the message to go away on its own, you don’t need the X button.

2 answers

6

To make Alert run for a certain period of time, use the setTimeout function. As in the example:

$("#erro").show();
setTimeout(function () {
  $("#erro").hide();
}, 3000);

In case, this '3000' means it will run for 3 seconds until it disappears, you can change as you wish.

  • 1

    It worked, thank you!

2

It is not necessary to use a library (85KB) for so little, 6 lines of javascript (220 bytes) solve.

    setTimeout(function () {
      document.getElementById("erro").style.display = "none";
    }, 3000);
    function hide(){
    document.getElementById("erro").style.display = "none";
    }
 <div id="erro" class="alert alert-danger alert-dismissible fade show">
                        <button type="button" class="close" onclick="hide()">&times;</button>
                        IP fora da faixa, por favor, digite dois IP's válidos
 </div>

  • @dvd, is that you do not know that it has configured to empty the cached files every time it closes the browser, capiche? If that’s your case too, I can provide you with min with only 165 bytes rsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.