preventDefault() not working on keyup event [jQuery]

Updated on May 1, 2022

I have developed an application that uses CodeMirror editor which by default creates a new line upon hitting the Enter key. I also detect the Shift+Enter on keyup event to carry out a different operation as shown below:

$("#editor + .CodeMirror").bind('keyup',function(event) {
//Check if Enter key is pressed
if (event.keyCode === 13 || event.keyCode === 186) {
          //do something

}
if (event.keyCode == 13 && event.shiftKey)
{
         //some business logic
         event.preventDefault()   //not working
}
});

But I don’t want Shift+Enter to create a new line in the editor. I understand that event.preventDefault() method will prevent the default action of the event, but it does not seem to work.

Why event.preventDefault() is not working on keyup event?

The preventDefault() method will not work in keyup event, because it is fired after the default event has already occurred. So listening to keyup event is too late for calling preventDefault. Instead listening to keydown or keypress event will solve the issue. Here’s the modified code.

$("#editor + .CodeMirror").bind('keydown',function(event) {
//Check if Enter key is pressed
if (event.keyCode === 13 || event.keyCode === 186) {
//do something

}
if (event.keyCode == 13 && event.shiftKey)
{
//some business logic
 event.preventDefault() //this will work
}
});

Was this article helpful?

Related Articles

Comments Leave a Comment

Leave a Comment