Jump to content

jQuery bind and unbind, unbind seems to work, but bind does not


godsent

Recommended Posts

You're not binding anything to the click event. As you're using an anonymous function, when it's unbound it no longer exists. What you should do is bind the click event to a named function, so it's easy to re-bind later:

 

http://jsfiddle.net/kBMfL/

 

Note the added unbind() within the re-bind, to prevent clicking the blue image multiple times binding the handler multiple times.

Just a word of warning by the way, unbinding events like you are doing can cause some unexpected results. As you unbind() the event, this will unbind everything. If you have multiple selectors pointing to the same element, that both bind a click event, then using unbind() will remove them both. Just letting you know to save yourself some possible headaches later. Personally I would use a logical approach to this, instead of removing the event. Perhaps set a property within the object when it's clickable.

 

For example:

 

$('#image1').click(function() {
    if (this.clickable || typeof(this.clickable) == 'undefined') {
        alert('Show for the first time.');
        this.clickable = false;
    }
});

$('#image2').click(function() {
    alert('Now allow to click one more time on first.');
    $('#image1')[0].clickable = true;
});

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.