Ryan King
Ryan King

Reputation: 3696

javascript prevent default for keyup

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')?

Upvotes: 18

Views: 38309

Answers (2)

SivaRajini
SivaRajini

Reputation: 7375

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

Upvotes: 8

LetterEh
LetterEh

Reputation: 26696

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.

Upvotes: 48

Related Questions