jQuery UI Replacement for alert()

The Javascript alert(message) is a simple one-liner to show a message on a web page. It uses a standard system dialog box to display the message. On a site where most other UI elements are built using jQuery UI it is more natural to display the alerts in the same style. Unfortunately there is no built in one-liner for displaying a simple alert in jQuery UI, but it is easy to add an own one.


This is a standard jQuery UI dialog displayed using one line of code. It follows the same theme as the rest of the jQuery UI widgets used on the site and it behaves like a normal modal dialog. The code used for displaying the dialog is $.alert("message", "title"), which is a jQuery extension I added with a few lines of code.

Adding the $.alert(message, title) Function

To add the $.alert(message, title) function a few lines of code are needed. You can put them in a separate file which is loaded after the jQuery and jQuery UI files or in an existing script file. The code should be placed directly in the file, not inside a document ready event handler.

1
2
3
4
5
6
7
8
9
10
$.extend({ alert: function (message, title) {
  $("<div></div>").dialog( {
    buttons: { "Ok": function () { $(this).dialog("close"); } },
    close: function (event, ui) { $(this).remove(); },
    resizable: false,
    title: title,
    modal: true
  }).text(message);
}
});
  1. Extend jQuery by adding a new alert function.
  2. Create a jQuery UI dialog on the fly, without using any existing element in the html code, through the "<div><div>" selector. The div is automatically inserted in the DOM in the end of the body.
  3. Add an Ok button which closes the dialog.
  4. Add a close event handler, which removes the div from the DOM. Without this, the DOM will get a hidden div added each time the dialog is shown.
  5. Disable resizing.
  6. Add the title.
  7. Make the dialog modal.
  8. Set the message text.

20 comments

  1. The confirm dialog is a little bit more tricky since it is a blocking call.
    However if you can accept passing the OK action as function instead of checking the return value you can simply rewrite the above dialog as:

    // Create a jquery style modal confirm dialog
    // Usage:
    //    $.confirm(
    //        "message",
    //        "title",
    //        function() { /* Ok action here*/
    //        });
    $.extend({
        confirm: function(message, title, okAction) {
            $("").dialog({
                // Remove the closing 'X' from the dialog
                open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }, 
                buttons: {
                    "Ok": function() {
                        $(this).dialog("close");
                        okAction();
                    },
                    "Cancel": function() {
                        $(this).dialog("close");
                    }
                },
                close: function(event, ui) { $(this).remove(); },
                resizable: false,
                title: title,
                modal: true
            }).text(message);
        }
    });
    1. Very nice the function, but I have a problem and not find any clue to solve.
      When the confirm dialog box open, its open at the click position. Can you help me?

    2. Nice extension, but how can use asp.net button and show message without using alert function.

      1. Everything described in this post is client side JavaScript. If you’re using web forms (which i assume when you write “asp.net button”), you should create a plain

  2. Nice tutorial. Thought you’d be interested to see the code i use for this as it allows you to use the standard JavaScript call alert to display the message.

    $(function(){
     $.getScript('http://code.jquery.com/jquery-1.8.3.js');
      $.getScript('http://code.jquery.com/ui/1.10.0/jquery-ui.js');
    window.alert = function (message) {
    		  $.getScript('http://code.jquery.com/jquery-1.8.3.js');
      $.getScript('http://code.jquery.com/ui/1.10.0/jquery-ui.js');
      var overlay = $('', {id:'overlay'});
     
    $('').html(message).dialog({
          modal: true,
    	  resizable: false,
          title: 'Alert!'
          });
    };});

    Using this all you have to do is call an alert in the normal way and it will display the jQueryui dialog.

    Hope someone finds this useful :)

    1. Nice extension, but I am a bit reluctant to override the build in alert(). The execution behaviour is way different, as the jQuery UI dialog doesn’t halt the current script’s execution in the same way as alert() does. When debugging the real alert() is a must to use.

      Another thing is that your code doesn’t remove the added html from the DOM once the dialog is dismissed. If used many times, the DOM will be growing. In my code above, the close handler for the dialog removes it from the DOM.

    1. If you want to use html formatting in the message, just change .text(message) to .html(message) instead. Be careful though that you are only using safe input to method or you could open your site to cross site scripting attacks.

  3. Does anyone use Alert for debugging in javascript ? i think something like if(console){console.log(‘What ever to debug’);} is a better solution than alert.

    1. Sometimes you need to check order of some actions (race condition) and console sometimes does not output the messages in same order as send (another race condition problem).
      Alert (thanks to the processing stop) is always displayed in order you call it.
      Also some devices does not have the console!

  4. I tried to center the dialogue in the page, it is always sticked to the bottom of the page, because the element is always added at the end of DOM. Any solutions?

  5. >>The execution behaviour is way different, as the jQuery UI dialog doesn’t halt the current script’s execution in the same way as alert() does.

    Is there any way to block the code execution while a modal dialog is used. Actually, i would like to replicate window.alert in dojo/jquery (should block UI as well as code execution). I can use the window.alert, but it doesn’t suit the framework theme.

    1. No, there is no way to alter that. When using a DOM-based alert such as jQuery UI’s dialog, the content is rendered rendered asynchronously after the function has returned. So even if there was a way to wait for input, that would mean the dialog wouldn’t show up.

  6. Very neat, both alert() and confirm(). I discovered this post while searching for something that would allow me to use HTML in the alert body, and obviously replacing the .text(message) method call with .html(message) does exactly that.

  7. Hi,
    iam using the above to leverage js alert and confirm functionality – somehow the replacement for alert works perfectly but confirm doesnt work and no error is shown what could be the issue?

    after global declaration iam calling it as below

    $.confirm(
    “Hello world”,
    “to confirm”,
    function() { /* Ok action here*/
    });

    regards

  8. Is there a way to show this Alert on top of a Pop up Window?
    I have two functions, one for the parent and one for the child window. Each have it own name.
    I’ve added a class to Child function the and I can control the text color but not the z-index.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.