Jquery dialog box confirmation box: appear when the user clicks an item


I am trying to create a jquery dialog confirmation box. In the case below, when I click on "click for confirmation box", the dialog box should appear. This should then disappear when the user selects ok or cancel, passing the information about what button was pressed to the calling function.

I have essentially copy-pasted the code below from a separate solution with the following change: I call myConfirm from inside another function - the one called when "click for.." is clicked. I don't just want the dialog box to appear when the page is loaded (which seems to be the case of most examples I've seen). The result is that the dialog box does not appear at all. Also, if I do call myConfirm directly in the script, then it doesn't close when I press a button. I've tried "close" instead of "destroy"


    <meta charset="utf-8" />
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="/resources/demos/external/jquery.bgiframe-2.1.2.js"></script>
    <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />

<a id = "confirm"> click for confirm box</div>


function myConfirm(dialogText, okFunc, cancelFunc, dialogTitle) {
        $('<div style="padding: 10px; max-width: 500px; word-wrap: break-word;">' + dialogText + '</div>').dialog({
            draggable: false,
            modal: true,
            resizable: false,
            width: 'auto',
            title: dialogTitle || 'Confirm',
            minHeight: 75,
            buttons: {
                OK: function () {
                    if (typeof (okFunc) == 'function') { setTimeout(okFunc, 50); }
                Cancel: function () {
                    if (typeof (cancelFunc) == 'function') { setTimeout(cancelFunc, 50); }

 $('[id=confirm]').click(function () {
 myConfirm( 'Do you want to delete this record ?',
           function () {
                 alert('You clicked OK');
        function () {
            alert('You clicked Cancel');
        'Confirm Delete'


I have tried your code with jsfiddle.net and it works fine.

Your mistake is that you attach the eventhandler while the document is still loading. You have to wait for the document to become ready by using the ready() event.

Also, you could simplify a bit by using the # selector for selecting your element by id:

$(document).ready(function() {
    $('#confirm').click(function () { ...

Another thing: Why are you starting a timer when executing the okFunc and cancelFunc? This should work without setTimeout:

OK: function () {
                   if (typeof (okFunc) == 'function') { okFunc(); }