Maria Jane Maria Jane - 2 months ago 7
Javascript Question

remove event of keydown from selector doesn't work?

I use keydown on one of my element, but I want to unbind it if it doesn't fit into my condition. But I used

off()
and
unbind
it doesn't seem to work. The alert of still got trigged, I wonder why.

if (imgDOM.naturalWidth > imgDOM.naturalHeight) {

$('#caption').attr('maxlength', 220);

$("#caption").keydown(function(e) {
if ((e.keyCode == 10 || e.keyCode == 13)) {
e.preventDefault();
alert('Landscape photo is allowed to have only single line of message.');
return false;
}
});

} else {
$('#caption').off('keydown', function() { //this won't work
limit_lines_for_potrait();
})
}

DBS DBS
Answer

You're using .off() as if it's listening for a new event, the function handler in this case is a refernce to the function to unbind, not a function that's run when after unbinding. limit_lines_for_potrait() should be the function you want to remove, but your original bind uses an anonymous function which you can't reference.

Assuming you have no other binds on the same element and event, you could simplify this to: $('#caption').off('keydown'); Which will unbind all listeners for that element and event type.

To run the function after, simply call that function:

} else {
  $('#caption').off('keydown');
  limit_lines_for_potrait();
}

Since the unbind isn't a listener, you don't need to wait for a callback, it will always be executed before the next line runs.

Comments