6

I have 2 buttons

 $(".button1").on("click", function(event){
 $(".button2").on("click", function(event){

What I would like to do is start with button1 as clicked and have no event listener, when button2 is clicked the event listener is removed and the event listener for button 1 is activated.

This is a fairly common technique is in actionscript 3 with the method removeEventListener() and would like to use a similar method or technique in jquery.

mttrb
  • 8,297
  • 3
  • 35
  • 57
LeBlaireau
  • 17,133
  • 33
  • 112
  • 192

3 Answers3

8

If you want to remove an event handler bound with jQuery.on then you probably want jQuery.off

http://api.jquery.com/off/

Petah
  • 45,477
  • 28
  • 157
  • 213
5

on() method bind event and off() unbind it. If you give parameter to off() it will unbind only supplied event, but without parameter unbind all events.

    $('.button1').on('click', function() {
        console.log('button1');
        $(this).off('click');
        $('.button2').on('click');
    })
    $('.button2').on('click', function() {
         console.log('button2');
        $(this).off('click');
        $('.button1').on('click');
    })
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

This is what I have but it does not put the event listener back on

 $(".slide1").on("click", function(){
    $(this).addClass('on');
    $('.slide2').removeClass('on');
     $(this).off('click');
    $('.slide2').on('click');
});

$(".slide2").on("click", function(){
    $(this).addClass('on');
    $('.slide1').removeClass('on');
    $(this).off('click');
    $('.slide1').on('click');
});
LeBlaireau
  • 17,133
  • 33
  • 112
  • 192