Fuiba Fuiba - 6 months ago 40
Javascript Question

jQuery unbind click event doesn't work

I want to disable the click event on a button if my link has the class "rebind".
I have tried in this way (jsFiddle: http://jsfiddle.net/D6Qh5/ ):

$('#button').bind('click', function(){
$(this).after('<span> click is active</span>');
$('span').fadeOut(1000);
});

$('#toggle').toggle(
function(){
$(this).text('rebind').removeClass('unbind').addClass('rebind');
},
function(){

$(this).text('unbind').addClass('unbind').removeClass('rebind');
}
);

if($("#toggle").hasClass("unbind")) {
$('#button').bind('click');
}
else {
$('#button').unbind('click');
}


But the unbind doesn't work and I don't get any error on Firebug. I do not know what I did wrong.

Any help is appreciated! Thank you!

Answer

Your bind, unbind methods are misplaced.

$('#button').on('click', Button_Click);

function Button_Click(){
    $(this).after('<span> click is active</span>');
    $('span').fadeOut(1000);
}

$('#toggle').toggle(
    function(){
        $(this).text('rebind').removeClass('unbind').addClass('rebind');
            $('#button').unbind('click');

    },
    function(){

     $(this).text('unbind').addClass('unbind').removeClass('rebind');
            $('#button').bind('click',Button_Click);
    }
);

http://jsfiddle.net/FtATg/
Also as of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.

Comments