7

How can i disable and enable a on click event.

I tried with:

$('#web').on('click', function web_function(event){
    event.stopPropagation();
    // execute a bunch of action to preform
});
$('#web').off('click'); // click is succesfully removed
$('#web').on('click'); // doesnt work, i need to redefine the actions to perform

Also I tried disabling with:

$('#web').unbind('click'); // click is succesfully removed
$('#web').bind('click'); // nok

But this also doesnt work...

So, i would like to disable/enable the click event without the need to redefine the actions to perform. Some sort of toggle... (click on/off)

And how do i implement the event to stop propagation?

How can i do this?

1
  • 1
    You have to pass in the callback when you are re-binding the event too. Commented Nov 7, 2012 at 18:57

2 Answers 2

15

You need to pass the handler function as the argument whenever you bind (or rebind).

In your case, you can name the function which you can use to pass it any time you re-bind again.. see below,

var myFunc = function(event){
     event.stopPropagation();
     // execute a bunch of action to preform
}

$('#web').on('click', myFunc); //bind myFunc
$('#web').off('click'); // click is succesfully removed
$('#web').on('click', myFunc); //rebind again
Sign up to request clarification or add additional context in comments.

3 Comments

I edit my question a little bit... i overlooked the event i'm using... can you show me how to implement this in your example?
can you just approve my edit? if its correct? then your answer meets my question :-)
@Nomistake I didn't reject it.. stackoverflow.com/suggested-edits/457236 however updated it.. thanks
3

first disable the element using prop() method of jQuery, i.e.

$("selector").prop("disabled",true);

and when you want to enable click the just do it by using

$("selector").prop("disabled",false);

2 Comments

if I use attr instead of prop, will it attach previously attached onclick event as well?
as per official docs "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method." using attr() is not a standard way for setting dom properties.

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.