How do I explicitly execute default action from jQuery event

I'm doing something similar and this works fine for me:

$('#link').click(function(e){
    if(!confirm('Are you sure you want to asdf?')){
        e.preventDefault();
    }
});

Using the suggestion Alexey Lebedev made in his second comment, my current implementation now looks like the sample below, except that I've also added my own implementation of localization for the button labels.

Notes:

  • I'm now using a jqueryUI dialog widget
  • Note the use of .delegate so that the handler is "ajax-aware", i.e. works on elements added to the DOM after the page is loaded, e.g. as a result of an AJAX call
  • Uses a flag to prevent recursion when the user clicks Yes on the confirm dialog.
  • Uses jquery 1.6.4 and jquery-ui-1.8.16

If anyone can suggest improvements, please chime in.

<!-- Examples of usage -->
<input type='submit' data-confirm="OK to delete customer 123?" ... />
<a href="..." data-confirm="OK to navigate?" ... />

<!-- Implementation -->
<script type="text/javascript">
    var confirmClickHandler = function (event) {
        if ($(event.currentTarget).data('isConfirming')) return;
        var message = event.currentTarget.attributes['data-confirm'].value;
        event.preventDefault();
        $('<div></div>')
                .html(message)
                .dialog({
                    title: "Confirm",
                    buttons: {
                        "Yes": function () {
                            $(this).dialog("close");
                            $(event.currentTarget).data('isConfirming', true);
                            event.currentTarget.click();
                            $(event.currentTarget).data('isConfirming', null);
                        },
                        "No": function () {
                            $(this).dialog("close");
                        }
                    },
                    modal: true,
                    resizable: false,
                    closeOnEscape: true
                });
    };

    $(document).ready(function () {
        $("body").delegate("[data-confirm]", "click", confirmClickHandler);
    });
</script>

Tags:

Events

Jquery