Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple click events firing JQuery

Tags:

Here's the scenario, my content is loaded asynchronously based on a class. So if I have a link with the class ajaxLink it fires as below:

$('a.ajaxLink').click(function (e) {         e.preventDefault();         var container = $(this).parents('div.fullBottomContent');         var href = $(this).attr('href');         container.fadeOut('fast', function () {             $.ajax({                 url: href,                 dataType: "html",                 type: "GET",                 success: function (data) {                     container.html(data);                     BindEventHandlers();                     container.fadeIn();                     $.validator.unobtrusive.parse('form');                 },                 error: function () {                     alert('An error has occurred');                 }             });         });      }); 

All lovely. Now in one instance I want to display a warning to the user to confirm that they want to load the page and loose all their changes so I've written this:

$('a.addANewHotel').click(function (e) {         if (!confirm('Adding a new hotel will loose any unsaved changes, continue?')) {             e.stopPropagation();         }     }); 

now I've tried return false, e.preventDefault() and e.stopPropagation(); but no matter what the first method is always fired? How can I prevent the extra click event from firing? Is this an order of events thing?

Don't see how this is relevant but my HTML is:

<a style="" href="/CMS/CreateANewHotel?regionID=3&amp;destinationID=1&amp;countryName=Australia" class="button wideBorderlessButton ajaxLink addANewHotel">Add a new hotel</a> 
like image 517
Liam Avatar asked Oct 03 '12 12:10

Liam


People also ask

How to avoid event bubbling in jQuery?

The event. stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

Why is this jQuery Ajax click event firing multiple times?

This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.


1 Answers

Have you tried: event.stopImmediatePropagation?

I believe it is what you are looking for:

http://api.jquery.com/event.stopImmediatePropagation/

$('a.addANewHotel').click(function (e) {         if (!confirm('Adding a new hotel will loose any unsaved changes, continue?')) {             e.stopImmediatePropagation();             e.preventDefault();         }     }); 
like image 67
bstakes Avatar answered Oct 07 '22 09:10

bstakes