test
test

Reputation: 2466

jQuery disable enable event handler of link

here is the code: http://jsfiddle.net/4WyPq/

So basically when I click 'button1' it animates then disables the button, after that I need to press button2 and enable the 'button1' event so I press again 'button1' it should do the same event.

Upvotes: 1

Views: 2409

Answers (3)

jfriend00
jfriend00

Reputation: 707298

When you bind a click event to a link, you HAVE to include the click handler function.

$(this).bind('click');

does not do anything because there is no handler function. You would have to pass the click handler function again if you want to rebind it. You could do that by breaking the click handler out into it's own local function and then using that function each time you bind the click event. You could do that like this:

function bindA1(force) {
    var a1 = $('.a1');
    if (force || a1.hasClass("disabled")) {
        a1.click(function() {
            $(this)
                .addClass("disabled")
                .unbind("click")
                .animate({"top": "+=50px"}, "slow");
            return(false);
        }).removeClass("disabled");
    }
}

bindA1(true);

$('.a2').click(function () {
    bindA1();
    return(false);
});

Working demo here: http://jsfiddle.net/jfriend00/3kjaR/

If you really intend to enable and disable the handlers for links like this, it may be easier to just set a property that you check rather than actually remove the event handlers.

You could use a flag like this:

$('.a1').click(function (){
    if (!$(this).data("disabled")) {
        $('.a1').animate({"top": "+=50px"}, "slow");
        $(this).data("disabled", true);
    }
});

$('.a2').click(function (){
    $(".a1").data("disabled", false);
});
​

Working demo here: http://jsfiddle.net/jfriend00/NSZ8P/

Upvotes: 2

Eric Hodonsky
Eric Hodonsky

Reputation: 5897

I played with your fiddle, and gave you a different option, instead of messing with the memory locations for the bind event and having to get all confused... try this:

http://jsfiddle.net/4WyPq/2/

$('.a1').click(function (){
    if(!$(this).hasClass("disabled")){
        $(this).addClass("disabled");
        $('.a1').animate({"top": "+=50px"}, "slow");
    }
});

$('.a2').click(function (){
    $(".a1").removeClass("disabled");
});

Upvotes: 0

Joseph
Joseph

Reputation: 119837

  • use .off() to remove the handler
  • use .on() to bind it again
  • use a reusable function for binding

demo:

$(function() {

    function clickHandler() {
        $(this).animate({
            "top": "+=50px"
        }, "slow").off('click');
        return false;
    }

    $('.a1').on('click', clickHandler);

    $('.a2').on('click',function() {
        $('.a1').on('click', clickHandler);
        return false;
    });
});​

Upvotes: 2

Related Questions