how to realize an alert that disappears after some seconds

3.1k views Asked by At

I am struggling trying to find a way to create an alert that opens when you click a button and then should disappear after an amount of time that can be set as a parameter.

so far I have this:

<script>
function myFunction() {
    alert("I will think later what to write here");
}

</script>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    $(".item_add").click(function(){
        myFunction();
    });
});
</script>

How should I change the code to achieve the result?

Thank you all for the help!

1

There are 1 answers

0
nicholaswmin On BEST ANSWER

You need to build the dialog yourself using HTML elements.

After this is done you should check setTimeout() that will allow you to perform a function after a preset period of time - e.g visibility:hidden your custom dialog.

var hideTimeout = 1000; //how many ms to wait before hiding after displaying

function customAlert() {

  //display the box
  var customAlert = document.getElementById("custom-alert-1");
  customAlert.style.visibility = 'visible';

  //set up a timer to hide it, a.k.a a setTimeout()
  setTimeout(function() {
    customAlert.style.visibility = 'hidden';
  }, hideTimeout)
}
body {
  text-align: center;
}
button {
  display: block;
  margin: 0 auto;
  margin-top: 32px;
}
.custom-alert {
  display: inline-block;
  visibility: hidden;
  background-color: #666;
  color: #fff;
  text-align: enter;
  margin: 5% auto;
  padding: 12px 48px;
}
<div id='custom-alert-1' class="custom-alert">Hello World</div>
<button onclick="customAlert()">Click to alert</button>

Since you are using jQuery you can substitute the visibility toggling for a $('#custom-alert-1').fadeOut() which provides a more streamlined show/hide effect.


If you are talking about the 'native' alert() then that won't ever work as JS does not have any access to it in any way apart from popping it open