Dunhamzzz
Dunhamzzz

Reputation: 14808

Prevent one jQuery Event with another

In order to tidy up my jQuery, I am looking to create a "confirm" class for various elements with event handlers so I can fire off a quick confirmation box so the user can confirm their action.

If the user clicks cancel on the confirmation box, any following events should be cancelled, but this should not be permanent, eg triggering the event again should bring up the confirmation and start again. If I can work this out I can make any sensitive action have a confirmation question to make sure the user meant to click.

For example:

$('.confirm').click(function() {
    if(!confirm('Are you sure?')) {
        // Stop any other click events on $(this) from happening this instance.
    }
});

$('.clicker').click(function() {
    alert('it happened');
});

<a class="clicker confirm">Click me</a>

Desired output would be that cancelling the confirmation would cancel the click event, but not totally disable it.

Upvotes: 5

Views: 2193

Answers (2)

Vivek
Vivek

Reputation: 11028

$('.confirm').click(function() {     
return confirm('Are you sure?');
});

you can also use event.stopPropagation() in side your click event to stop furthure propagation.

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

You can use event.stopImmediatePropagation() from jQuery:

$('.confirm').click(function(event) {
    if(!confirm('Are you sure?')) {
        event.stopImmediatePropagation();

        // Stop any other click events on $(this) from happening this instance.
    }
});

$('.clicker').click(function() {
    alert('it happened');
});

Look at test case on jsFiddle

Upvotes: 5

Related Questions