Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

bind click after unbind the click

I wanted to bind the click event after unbinding the click event. For eg. If you click on button one then this unbind this button and when you click in button two then it should bind the click event of button one again. But binding click event seems not working.

$('#one').on('click',function(){  <<----------------------  
    alert('one clicked');                                | 
    $(this).off('click');                             click
});                                                      |
$('#two').on('click',function(){                      event
    alert('two clicked');                                |
    $('#one').on('click'); >>---------not binding the-----
});

demo


Ps: without using flagged variable.

Upvotes: 1

Views: 222

Answers (3)

Somnath Kharat
Somnath Kharat

Reputation: 3610

I just tried and its work great now.You can use bind

$('#one').on('click',clickevent);

function clickevent(){    
    alert('one clicked');                                
    $(this).off('click');                  
}                                                     
$('#two').on('click',function(){                      
    alert('two clicked');                                
    $('#one').bind('click',clickevent); 
});

Jsfiddle

Upvotes: 0

Adil
Adil

Reputation: 148120

Define a click handler instead of binding with anonymous function. Binding click method using on need to provide the the event handler which you did not provide in #two click handler.

If you look at the documentation of on, .on( events [, selector ] [, data ], handler(eventObject) ) you will see the handler is not optional here.

You can pass false in place of handler but that means you have a function that simply returns false.

A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false, jQuery api.

$('#two').on('click',oneclickhandler);

$('#two').on('click',function(){
    alert('two clicked');
    $('#one').on('click', oneclickhandler);
});

function oneclickhandler(){
    alert('one clicked');
    $(this).off('click');
});

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Use a named handler and use .one() to register the handler

function handler() {
    alert('one clicked');
}
$('#one').one('click', handler);
$('#two').on('click', function () {
    alert('two clicked');
    $('#one').on('click', handler);
});

Demo: Fiddle

Upvotes: 0

Related Questions