5

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,046
  • 2
  • 32
  • 54
LeBlaireau
  • 14,709
  • 30
  • 95
  • 169

3 Answers3

7

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

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

Petah
  • 42,792
  • 26
  • 149
  • 203
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
  • 81,835
  • 21
  • 131
  • 160
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
  • 14,709
  • 30
  • 95
  • 169