Search code examples
javascriptpreventdefaultkeyup

Prevent default writting letter


I would like to add function, when I hit "L" something happens, BUT the L won't be written.

Mapping function to L letter works fine, but even when I added prevent default to function, L letter is always written into textarea when I set cursor inside it. Can be this solved please?

<html>

<body>
<textarea id="a">Test</textarea>
<textarea id="ab"></textarea>

<script>
function send(e) {
            if (e.keyCode == 76) {
                e.preventDefault();
                ab.value += a.value;
                a.value = "";
            }
        }
        document.addEventListener('keyup', send);
        
</script>
</body>

</html>

Solution

  • The pressed key will be inserted once the keypress event completes. A keyup listener will run after the key has been inserted, so calling preventDefault on the event doesn't prevent the key from appearing.

    Add a keypress listener instead.

    function send(e) {
      if (e.keyCode == 76) {
        e.preventDefault();
        ab.value += a.value;
        a.value = "";
      }
    }
    document.addEventListener('keypress', send);
    <textarea id="a">Test</textarea>
    <textarea id="ab"></textarea>