I have an input type="image"
. This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image
is paired with, I setup an event handler for the input-image
. Then when the user clicks the image
, they get a little popup to add some notes to the data.
My problem is that when a user enters a zero into the text box, I need to disable the input-image
's event handler. I have tried the following, but to no avail.
$('#myimage').click(function { return false; });
The removeEventListener() method removes an event handler from an element.
Use the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.
The . off() method removes event handlers that were attached with .
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
With jQuery 1.7 onward the event API has been updated, .bind()
/.unbind()
are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,
$('#myimage').click(function() { return false; }); // Adds another click event $('#myimage').off('click'); $('#myimage').on('click.mynamespace', function() { /* Do stuff */ }); $('#myimage').off('click.mynamespace');
In your example code you are simply adding another click event to the image, not overriding the previous one:
$('#myimage').click(function() { return false; }); // Adds another click event
Both click events will then get fired.
As people have said you can use unbind to remove all click events:
$('#myimage').unbind('click');
If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:
$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });
and to remove just your event:
$('#myimage').unbind('click.mynamespace');
This wasn't available when this question was answered, but you can also use the live() method to enable/disable events.
$('#myimage:not(.disabled)').live('click', myclickevent); $('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });
What will happen with this code is that when you click #mydisablebutton, it will add the class disabled to the #myimage element. This will make it so that the selector no longer matches the element and the event will not be fired until the 'disabled' class is removed making the .live() selector valid again.
This has other benefits by adding styling based on that class as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With