How can I create a custom alert function in Javascript?
-
Can you be a little more descriptive? – Wallace Breza Aug 02 '10 at 21:22
-
1I want to change the default title from 'The page at http//...' to my own custom title. Is that possible? – Elliot Bonneville Aug 02 '10 at 21:29
6 Answers
You can override the existing alert
function, which exists on the window
object:
window.alert = function (message) {
// Do something with message
};

- 43,482
- 6
- 101
- 102
This is the solution I came up with. I wrote a generic function to create a jQueryUI dialog. If you wanted, you could override the default alert function using Matt's suggestion: window.alert = alert2;
// Generic self-contained jQueryUI alternative to
// the browser's default JavaScript alert method.
// The only prerequisite is to include jQuery & jQueryUI
// This method automatically creates/destroys the container div
// params:
// message = message to display
// title = the title to display on the alert
// buttonText = the text to display on the button which closes the alert
function alert2(message, title, buttonText) {
buttonText = (buttonText == undefined) ? "Ok" : buttonText;
title = (title == undefined) ? "The page says:" : title;
var div = $('<div>');
div.html(message);
div.attr('title', title);
div.dialog({
autoOpen: true,
modal: true,
draggable: false,
resizable: false,
buttons: [{
text: buttonText,
click: function () {
$(this).dialog("close");
div.remove();
}
}]
});
}

- 7,447
- 5
- 43
- 75
Technically you can change what the alert function does. But, you cannot change the title or other behavior of the modal window launched by the native alert function (besides the text/content).

- 31,171
- 11
- 57
- 63
-
Alright, that's what I needed to know. +1. But accepted advait's answer because he gave me an alternate solution. – Elliot Bonneville Aug 02 '10 at 21:39
If you're looking for a javascript/html/css replacement, I recommend checking out jQueryUI and its implementation of modal dialogs.
"override" way is not good enough, suggest you to create a custom popup box. The best benefit of this solution is that you can control every details.

- 1,340
- 17
- 7
-
[Simple Popup](https://github.com/dabeng/Simple-Popup) is another lightweight alternative for you. – dabeng Feb 06 '16 at 03:05
-
No, you can not using the default alert. Not even formating. But, I recomend you using Sweet alert to do that.

- 1,159
- 15
- 29