Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  23] [ 1]  / answers: 1 / hits: 91303  / 15 Years ago, thu, december 17, 2009, 12:00:00

How can I temporarily disable the onclick event listener, (jQuery preferred), after the event has been fired?



Example:



After the user clicks on the button and fires this function below, I want to disabled the onclick listener, therefore not firing the same command to my django view.



$(.btnRemove).click(function(){
$(this).attr(src, /url/to/ajax-loader.gif);
$.ajax({
type: GET,
url: /url/to/django/view/to/remove/item/ + this.id,
dataType: json,
success: function(returned_data){
$.each(returned_data, function(i, item){
// do stuff
});
}
});


Thanks a lot,



Aldo


More From » jquery

 Answers
35

There are a lot of ways to do it. For example:



$(.btnRemove).click(function() {
var $this = $(this);
if ($this.data(executing)) return;
$this
.data(executing, true)
.attr(src, /url/to/ajax-loader.gif);
$.get(/url/to/django/view/to/remove/item/ + this.id, function(returnedData) {
// ... do your stuff ...
$this.removeData(executing);
});
});


or



$(.btnRemove).click(handler);

function handler() {
var $this = $(this)
.off(click, handler)
.attr(src, /url/to/ajax-loader.gif);
$.get(/url/to/django/view/to/remove/item/ + this.id, function(returnedData) {
// ... do your stuff ...
$this.click(handler);
});
}


We can also use event delegation for clearer code and better performance:



$(document).on(click, .btnRemove:not(.unclickable), function() {
var $this = $(this)
.addClass(unclickable)
.attr(src, /url/to/ajax-loader.gif);
$.get(/url/to/django/view/to/remove/item/ + this.id, function(returnedData) {
// ... do your stuff ...
$this.removeClass(unclickable);
});
});


If we don't need to re-enable the handler after it has been executed, then we can use the .one() method. It binds handlers that are to be executed only once. See jQuery docs: http://api.jquery.com/one


[#98050] Sunday, December 13, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luzv

Total Points: 178
Total Questions: 105
Total Answers: 114

Location: Palau
Member since Tue, May 30, 2023
1 Year ago
;