Let’s say we have a simple div HTML element with attribute contenteditable. Sometimes we want to observe ENTER key and prevent cursor to go to new line when user hit ENTER key without SHIFT key. To do this you can use event onkeyup. See example how it works.

And? Yeah, the cursor is going to new line when you hit ENTER key. It’s relatively quick, but it’s still visible behavior. This is not exactly what we expecting. We do not what to move cursor to new line when user hit ENTER key without SHIFT key. Ok, why this happen?

It happens because first called event is “onkeydown” and then “onkeyup”. So, all we need is to move our code to “onkeydown” event and solve the problem. See example how it works.

Note: remember to cancel the event if it is cancelable, without stopping further propagation of the event. Otherwise browser will be continuing with default action. This can be done like this:

var elm = document.getElementById('test');
elm.onkeydown = function (e) {
    if (!e) {
        e = window.event;
    }
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
};

e.returnValue = false; is only for IE < 9. If you plan to do not support IE < 9 then you can skip this part of code.

Comments

You can leave a response, or trackback from your own site.

Before you add comment see for rules.

Leave a Reply

Your email address will not be published. Required fields are marked *

6w1n2s