How can I create an Alert in JavaScript that can be seen for 2 seconds and then close automatically (only) without the user clicking accept?
How can I create an Alert in JavaScript that can be seen for 2 seconds and then close automatically (only) without the user clicking accept?
I do it with the setTimeout function. In the following way.
$('#alert').fadeIn();
setTimeout(function() {
$("#alert").fadeOut();
},2000);
I present you with Toastr
, is a library in JavaScript
that generates notifications in a " modern ":
toastr.options = {
"debug": false,
"positionClass": "toast-bottom-right",
"onclick": null,
"fadeIn": 300,
"fadeOut": 100,
"timeOut": 5000,
"extendedTimeOut": 1000
}
var showToastrs = false;
function toastrs() {
if (!showToastrs) {
toastr.error('Estamos bajo ataque DDoS', 'Error Critico!');
toastr.success('Se guardaron los cambios satisfactoriamente', 'Todo en orden');
toastr.warning('La latencia del server esta aumentando.', 'Alerta!');
} else {
toastr.error('no se puede!\'t.', 'Otro error crítico');
}
}
// Definimos los callback cuando el TOAST le da un fade in/out:
toastr.options.onFadeIn = function() {
showToastrs = true;
};
toastr.options.onFadeOut = function() {
showToastrs = false;
};
$(function() {
$("#clear").on("click", function() {
// Clears the current list of toasts
toastr.clear();
});
$("#rewind").on("click", function() {
// show toastrs :)
toastrs();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://codeseven.github.com/toastr/toastr.js"></script>
<link href="http://codeseven.github.com/toastr/toastr.css" rel="stylesheet"/>
<link href="http://codeseven.github.com/toastr/toastr-responsive.css" rel="stylesheet"/>
<a href="http://codeseven.github.io/toastr/demo.html" target="_blank">Toastr official demo</a>
<br/>
<br/>
<input id="clear" type="submit" value="Limpiar notificaciones">
<input id="rewind" type="submit" value="Mostrar notificaciones">
I see that you want to open and close the message, with Javascript this can not be done, closing the message has to be manually.
Another option is to show a window with the message and close it automatically after 2 seconds (2000 ms).
<html>
<body>
<p>Abre un mensaje que se cerrara en 2 segundos.</p>
<button onclick="ejecutaAlerta()">muestra mensaje</button>
<script>
function ejecutaAlerta() {
var w = window.open('','','width=100,height=100')
w.document.write('Hola StackOverflow!')
w.focus()
setTimeout(function() {w.close();}, 2000)
}
</script>
</body>
</html>
Whoever calls the function is the setTimeOut () method:
setTimeout () Perform a function, after waiting for a number specific milliseconds.
Another option that can help you is JQuery jGrowl
I'll give you an example with a duration of 2 seconds:
$.jGrowl("Hello world!",{ life : 2000});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.1/jquery.jgrowl.min.js"></script>
If you need something more "modern" I recommend toastr
I like the solution of @fredyfx but if you care about the upload speed and the resources used by your app you can implement something similar in fewer bytes by only putting the functions you are going to use.
This is an example, of course the styles can be adjusted to the aesthetics of your application and you can add more features. This is a base for writing your own component without having to load long libraries that result in heavy applications.
(function(window, document) { // asilamos el componente
// creamos el contedor de las tostadas o la tostadora
var container = document.createElement('div');
container.className = 'toast-container';
document.body.appendChild(container);
// esta es la funcion que hace la tostada
window.doToast = function(message) {
// creamos tostada
var toast = document.createElement('div');
toast.className = 'toast-toast';
toast.innerHTML = message;
// agregamos a la tostadora
container.appendChild(toast);
// programamos su eliminación
setTimeout(function() {
// cuando acabe de desaparecer, lo eliminamos del dom.
toast.addEventListener("transitionend", function() {
container.removeChild(toast);
}, false);
// agregamos un estilo que inicie la "transition".
toast.classList.add("fadeout");
}, 2000); // OP dijo, "solo dos segundos"
}
})(window, document);
// ejempo de uso
doToast("Hola mundo!");
// ejemplo retardado de uso
setTimeout(function() {
doToast("Soy una tostada");
}, 1200);
.toast-container {
position: fixed;
width: 150px;
right: 0;
top: 0;
bottom: 0;
z-index: 10; /* sobre todo lo demás */
}
.toast-toast {
font-size: 250%;
margin-bottom: 3px;
border-radius: 2px;
border: 1px green;
background: #98FF98;
text-align: center;
line-height: 1;
transition: all 0.5s;
}
.fadeout{
opacity: 0;
}
With the standard javascript alert I doubt you can do it, but if you use an alert implemented from jquery as being
You will see in the example that you implement a timer
, for example the title Alert Dialogs
define
$.alert('jqAlert is easy to use with alerts and its where I got my start.', {
title:'Alert Title Message',
icon:'',
customIcon:'icon-asterisk',
exception: 'Exception',
stack: 'Stack Trace',
timer:5000,
onTimeout:function() { },
onClose: function() { },
buttons:[
{
title:'Press Me',
callback:function() { $(this).dialog("close");}
}
]
});
You will see the% co_of% after that time it closes only