Adding/Removing click event on a span/label element

1.5k views Asked by At

Requirement:
I make a ajax call onclick of a span. I need to temporarily disable/remove the click event and enable it once my ajax request gets complete.

Incase of input buttons I used to:

onRequest : function() {
    $(inputID).disabled = true ;
},

onComplete : function(response) {
    $(inputID).disabled = false;
},

However incase of span/label since "disabled" wont work I need an alternative.

Worst case solution:

onRequest : function() {
    $(inputID).removeEvents() ;
},

onComplete : function(response) {
    $(inputID).addEvents() ;
},

I dislike this solution since I need to make provision to keep the arguments required by the method.

Is there any provision in JavaScript where I can swiftly temporarily disable/enable click events on span/label without removing and adding of events?

1

There are 1 answers

0
Ross On

You could add a class to the span (so you can style it to)...

$("inputID").on("click", function () {
    var $input = $(this);
    if (!$input.hasClass("loading")) {
        $input.addClass("loading");
        // pseudo code below
        $input.ajax({
            onComplete : function(response) {
                $input.removeClass("loading");
            }
        })
    }
});

Therefore you are not needing to add, remove or touch any events.