I have the following code:
$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
if(e.which == 13) {
e.preventDefault();
$(this).after('<p contenteditable = "true"></p>');
$(this).next('p').focus();
} else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
e.preventDefault();
alert("Should remove element.");
$(this).remove();
$(this).previous('p').focus();
};
});
I would like to prevent the default action when a key is pressed. preventDefault
works for keypress
but not keyup
. Is there a way to prevent the defualt for $(document).on('keyup')
?
I would create a flag or boolean variable called isKeyDown and set it to true when the key is down and false when the key is up. Then, in your keydown function, you can use an if conditional where if true, then skip otherwise run the function and set the value to true. On keyup, set the value to false.
click(function(event){ event. preventDefault(); }); $('#some_link'). unbind('click'); worked as the only method to restore the default action.
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
onkeyup = null; Inline event handler attributes are assigned to the oneventname property of the element, so just set it to null to detach the event listener.
No. keyup
fires after the default action.
keydown
and keypress
are where you can prevent the default.
If those aren't stopped, then the default happens and keyup
is fired.
We can prevent the action by using following code snippet.
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
e.cancelBubble = true;
return false;
keyup fires after keydown/keypress. we can prevent default action in anyone of those events.
Thanks,
Siva
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