jQuery unbind click event function and re-attach depending on situation

17,574

Solution 1

Simply make a named function. You can go low tech here and back to basics to unbind and reattach specific events.

function doStuff()
{
    if($(this).,next('.section').is(':visible'))
        ...
}

$('.header').on('click', doStuff);
$('.header').off('click', doStuff);

Solution 2

Instead of unbind and re-bind, I suggest you to add a simple class to .header and check for the class in the click handler. See below,

$('#printVers').click(function(){
   if($('#formVersion').val() != "Print")
   {
     $('.header').addClass('dontClick');
   } else  {
     $('.header').removeClass('dontClick');
   }
});

And in your .header click handler,

$('.header').click(function(){
     if ($(this).hasClass('dontClick')) {
        return false;
     }
     //rest of your code

If you insist on having a unbind and bind, then you can move the handler to a function and unbind/bind the function any number of time..

Solution 3

You can try something like this.

$('#printVers').click(function(){
   if($('#formVersion').val() != "Print")
   {
       $('.header').addClass('clickDisabled');
   }
   else
   {
       $('.header').removeClass('clickDisabled');
   }
});

And then in the click handler check for this class.

$(document).ready(function(){
    $('.section').hide();
    $('.header').click(function(){
        if(!$(this).hasClass('clickDisabled')){
            ...
            ...
        }
    });
});
Share:
17,574
Mark Walters
Author by

Mark Walters

Lead development Specialist for Royal Bournemouth Hospital working on front end UI's, eForms and automations

Updated on June 05, 2022

Comments

  • Mark Walters
    Mark Walters almost 2 years

    The code below I use to create a sliding menu. I need to know how to unbind the function attached to the click event and re-attach it some other time. (using jQuery 1.7.2)

    $(document).ready(function(){
        $('.section').hide();
        $('.header').click(function(){
          if($(this).next('.section').is(':visible'))
          {
            $('.section:visible').slideUp()              
            $('.arrows:visible').attr("src","right.gif")
          }
          else
          {
            $('.section').slideUp();
            $(this).next('.section').slideToggle();
            $(this).find('.arrows').attr("src","down.gif")
        });
    });
    

    The code below is what I have so far

    $('#printVers').click(function(){
       if($('#formVersion').val() != "Print")
       {
         $('.header').unbind('click');
       }
       else
       {
         //else re-attach functionality?
       }
    });
    

    Thanks