5

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This is what I intended to do. Messed up TWICE in my answer so decided to delete it instead ;) thanks for refreshing my mind!
I'd like to add, in the case of forms, event.preventDefault() is also required to stop the form from firing when you deny the confirmation.
0
$('.confirm').click(function() {     
return confirm('Are you sure?');
});

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

2 Comments

I found that return false didn't stop other click events from being triggered.
Sadly, .disablePropagation() doesn't exist. It was my bad, and it should be .stopPropagation(), which doesn't work either. Nicola presented the correct solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.