Fidèle à mes habitudes je vais essayer de partager de nouvelles choses utiles pour tout FrontEnd Developper qui se respecte (javascript, jQuery, css, html 5, mvc, php, ...).
Trève de bavardage, passons au sujet du jour : Modifier la façon d'afficher un alert() JavaScript.
Je me suis donné comme défi de rendre l'affichage de mes alert() JavaScript plus sexy dans mes applications web.
Voici le code résultant de mes recherches et de mes tests pour remplacer automatiquement l'affichage des vieux alert() JavaScript par de jolie jQuery UI dialog.
<!DOCTYPE html>
<html>
<head>
<!-- get jquery and jquery ui on google cdn -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/dot-luv/jquery-ui.css" />
<!-- create script that overwrite the browser alert() -->
<script type="text/javascript">
window.alert = function(native) {
return function(message) {
try {
// display the alert message with the jquery ui dialog
jQuery("<div>" + message + "</div>").dialog({
modal:true, resizable:false, draggable:false,
buttons: {
Ok: function() { $(this).dialog("close"); }
}
});
} catch(e) {
// display the alert with the native browser alert
native(message);
}
}
}(window.alert);
</script>
</head>
<body>
<h1>JavaScript Custom alert()</h1>
<p>
<!-- test to call the alert() function -->
<a href="#" onclick="alert('There is my beautiful alert !');return false;">Display an alert</a>
</p>
</body>
</html>
<html>
<head>
<!-- get jquery and jquery ui on google cdn -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/dot-luv/jquery-ui.css" />
<!-- create script that overwrite the browser alert() -->
<script type="text/javascript">
window.alert = function(native) {
return function(message) {
try {
// display the alert message with the jquery ui dialog
jQuery("<div>" + message + "</div>").dialog({
modal:true, resizable:false, draggable:false,
buttons: {
Ok: function() { $(this).dialog("close"); }
}
});
} catch(e) {
// display the alert with the native browser alert
native(message);
}
}
}(window.alert);
</script>
</head>
<body>
<h1>JavaScript Custom alert()</h1>
<p>
<!-- test to call the alert() function -->
<a href="#" onclick="alert('There is my beautiful alert !');return false;">Display an alert</a>
</p>
</body>
</html>
Testé avec IE6, IE7, IE8, IE9 x86, IE9 x64, Chrome 15, Firefox 8.