Default action not resetting on new call

62 views Asked by At

I am having some problems with preventdefault in JavaScript, specifically jQuery. I am trying to get a modal box to show with elements with a class of ".confirm" which effectively overrides the default action confirming with the user if they are sure they want to carry out that action before continuing with what it was set out to do.

$('.confirm').on('click', function(event, options)
{
    options = options || {};

    if (!options.confirmed)
    {
        vex.dialog.confirm({
            message: 'Are you sure that you want to perform this action?',
            callback: function(response) {
                if (response === true) {
                    $(event.target).trigger('click', {confirmed: response});
                }
            }
        });

        event.preventDefault();
    }

});

Flow

  • Show a modal dialog.
  • If the user confirms the action, the click event is fired again, only this time confirmed is passed back to the event handler.
  • This would then skip the check and continue with the default action.

Problem

But this is not the case as it seems that the default action is overriding any future calls from happening regardless.

Attempts

  • Un/Rebinding - requires the user to click it again for it to work.
  • window.location (not ideal as it assumes the action is a link but works)
  • confirm (doesn't tie in nicely with the aesthetics so needed a better solution)

Notes

  • Needs to be asynchronous.

Any help would be awesome as it has me stumped for the time being

2

There are 2 answers

4
Marcos González On

Put event.preventDefault before the API call, this should work I guess.

$('.confirm').on('click', function(event, options)
{
    options = options || {};

    if (!options.confirmed)
    {
        event.preventDefault();

        vex.dialog.confirm({
            message: 'Are you sure that you want to perform this action?',
            callback: function(response) {
                if (response === true) {
                    $(event.target).trigger('click', {confirmed: response});
                }
            }
        });


    }

});

EDIT:

I think this is the only way without unbind/rebind as you said.

$('.confirm').on('click', function(event, options)
{
    options = options || {};

    if (!options.confirmed)
    {
        event.preventDefault();

        vex.dialog.confirm({
            message: 'Are you sure that you want to perform this action?',
            callback: function(response) {
                if (response === true) {
                    $(event.target).trigger('click', {confirmed: response});
                }
            }
        });


    }
    else {
        window.location = $(this).attr("href");
    }

});
1
nabrown On

Try removing the click handler with $('.confirm').off() in your callback. This way, when you programmatically trigger the click, your click handler be called.