Changing the way a JavaScript Alert() or Prompt() looks
Is there any way to change the looks of an alert or prompt in JavaScript? Things like adding an image, changing the font color or size, and whatever will make it look different.
Expanding on Matthew Abbott's idea, it struck me that you want an answer that uses plain old Javascript without recourse to any frameworks. Here's a quick and dirty page that emits a div with a simple close button and the message presented in the centre:
Rough CSS for the alertBox and the alertClose button
#alertBox{
position:absolute;
top:100px;
left:100px;
border:solid 1px black;
background-color: #528CE0;
padding: 50px;
visibility: hidden;
}
#alertClose{
position: absolute;
right:0;
top: 0;
background-color: black;
border: solid 1px white;
color: white;
width: 1em;
text-align: center;
cursor: pointer;
}
Then some javascript to override the built-in alert function and provide a closing function to handle the click event on alertClose.
function closeAlertBox(){
alertBox = document.getElementById("alertBox");
alertClose = document.getElementById("alertClose");
alertBox.style.visibility = "hidden";
alertClose.style.visibility = "hidden";
}
window.alert = function(msg){
var id = "alertBox", alertBox, closeId = "alertClose", alertClose;
alertBox = document.createElement("div");
document.body.appendChild(alertBox);
alertBox.id = id;
alertBox.innerHTML = msg;
alertClose = document.createElement("div");
alertClose.id = closeId;
alertClose.innerHTML = "x";
alertBox.appendChild(alertClose);
alertBox.style.visibility = "visible";
alertClose.style.visibility = "visible";
alertClose.onclick = closeAlertBox;
};
Calling alert
, as Matthew Abbott suggested, now displays the div you've just created and clicking the x dismisses it by making it invisible.
alert("hello from the dummy alert box.");
To implement, you'd need to have a test in the alert function to make sure you're not re-creating the div a million times and you'd need to mess around with the CSS to make it fit your colour scheme etc, but that's the rough shape of how to implement your own alert box.
Seems like overkill to me and I agree with Matthew that doing it with some kind of dialog or modal element created with a famous framework like jQuery or YUI would be better and strangely easier in the long run.
The alert
and prompt
functions call APIs provided by the browser, so you won't have any control over how they look.
What you could do though is redefine those functions, and instead maybe use something like jQuery modal, eg:
window.alert = function(message) {
// Launch jQuery modal here..
};
window.prompt = function(message) {
// Launch jQuery modal here..
};
You can't modify that; but you can use something like showModalDialog
, it needs just an URI to load the hmtl/css form you want (if you can keep it in a separate page).