Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom alert using Javascript

Tags:

javascript

How can I create a custom alert function in Javascript?

like image 265
Elliot Bonneville Avatar asked Aug 02 '10 21:08

Elliot Bonneville


People also ask

Can I customize the alert in JavaScript?

You can create a custom function that'll replace the native alert() box in the user's web browser. You'll do this from the window object, and the custom function will work as such: Set constants for the alert title and alert button text.

How do you alert in JavaScript?

One useful function that's native to JavaScript is the alert() function. This function will display text in a dialog box that pops up on the screen. Before this function can work, we must first call the showAlert() function. JavaScript functions are called in response to events.

Can you put HTML in a JavaScript alert?

You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.


2 Answers

You can override the existing alert function, which exists on the window object:

window.alert = function (message) {
  // Do something with message
};
like image 57
Matt Avatar answered Oct 02 '22 20:10

Matt


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();
            }
        }]
    });
}
like image 22
Walter Stabosz Avatar answered Oct 02 '22 19:10

Walter Stabosz