0

I have the following code:

$('#button-a').click(function(){   
    $('#button-b').click(function(){
        alert('something');
    });
});
$('#button-b').click(function(){   
    // do something
});

How can I deactivate the nested #button-b function after I have clicked #button-a, so only the last #button-b function (not nested) activates when i click #button-b and not them both?

Jmumby Clasul
  • 441
  • 1
  • 7
  • 9

4 Answers4

1

Try this using .on() and .off() event handlers.

$('#button-a').click(function(){   
    $('#button-b').off('click');   //unbind the click event of the #button-b
    $('#button-b').click(function(){
        alert('something');
    });
});
$('#button-b').on('click',function(){   
    // do something
});
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

In order to accomplish this, your function cannot be anonymous. You need to use the form of off which specifies the handler to remove. Rewriting your code a bit, it'd look something like this:

function myFunc() {
    alert('something');
}

$("#button-a").click(function() {
    $("#button-b").click(myFunc);
});

$("#button-b").click(function() {
    // do something
});

To remove the handler, you'd use:

$("#button-b").off('click', myFunc);

I'm not quite sure where you want this to occur, but the above line of code will work anywhere that the DOM has been loaded and myFunc is in scope.

J David Smith
  • 4,780
  • 1
  • 19
  • 24
0

If you feel you definitely need an anonymous handler here, you can use event namespace for your task - http://api.jquery.com/on/

    $('#button-b').on('click.nestedClick', function(){
        alert('something');
    });
    // and unbind it at some point:
    $('#button-b').off('click.nestedClick');
    
amakhrov
  • 3,820
  • 1
  • 13
  • 12
0
$('#button-a').click(function(){   
    $('#button-b').trigger('click');
});
$('#button-b').click(function(){   
    // do something
});

Change your code like this so it call your last function for button-b when you click on button-a

GeniusJRS
  • 119
  • 2
  • 6