How to customize the Javascript's confirm() box

4.2k views Asked by At

How does stackoverflow customize the confirm() box's buttons and add custom text to the buttons?

enter image description here

All the other questions I looked at pointed at a random jQuery plugin to do this. Can this be done with Vanilla Javascript? If yes, then how?

1

There are 1 answers

6
Shai On BEST ANSWER

There are only specific messages/buttons you can offer the user, without using a custom alert box/plugin. They are:

  1. To display a message with just an OK button, by calling:

    window.alert('Message');
    
  2. To display a message with OK/Cancel as the options, by calling:

    var didTheyPressOK = window.confirm('Are you sure you want to XXXXX?');
    
  3. As StackOverflow does in your example, to display a Leave.../Stay... message on leaving the page, where pressing Stay causes the browser to stay on your page (the exact button wording is browser-dependent, you cannot control it):

    window.onbeforeunload = function() {
        // you may or may not want a condition here, e.g.
        // if (thereAreUnsavedChanges)
        return 'Are you sure you actually want to leave? You have unsaved changes...';
    }
    

For any other situation, you'll need to use some kind of alert plugin (or write one yourself :-/), as you speculated in your question.


Put simply, those buttons are browser specific and chrome automatically displays helpful text on the button to make things clearer. It happens with window.onbeforeunload if you return a string, which is displayed as a message before navigation.