Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 861
Ryan King Avatar asked Apr 17 '13 05:04

Ryan King


People also ask

How do I stop Keydown event?

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.

How do I stop event preventDefault?

click(function(event){ event. preventDefault(); }); $('#some_link'). unbind('click'); worked as the only method to restore the default action.

How do I prevent default?

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.

How do I get rid of Keyup event?

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.


2 Answers

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.

like image 177
Norguard Avatar answered Oct 16 '22 07:10

Norguard


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

like image 8
SivaRajini Avatar answered Oct 16 '22 06:10

SivaRajini