1

i want to listen for a key stroke, then output the pressed key into every span element inside class=letter element using jquery. at the same time i want to preserve basic functionality of the keyboard shortcuts native to the browser eg. shift + cmd + ]; cmd + r; ctrl + tab etc...

<div class="letter">
<span>a</span>
</div>

this jQuery works very well on detecting and outputing the keystrokes that i am after.

$(window).on("keypress", function (e) {
                var t = e.which || e.keyCode;
                if (e.which === 0 && e.keyCode > 0) return;
                    var n = String.fromCharCode(t);
                    $(".letter").find("span").html(n);

                e.preventDefault();
        });

now i need to exclude somehow the shortcuts but i want to keep the e.preventDefault(); line as it's muting the "wrong button" sound...

2
  • What key press specifically are you trying to detect? Commented Apr 5, 2014 at 15:22
  • letters, numerals, anything accessible from keyboard that can be represented as a glyph. Commented Apr 5, 2014 at 15:43

1 Answer 1

1

Maybe all you need to do is detect the alt, ctrl and meta keys (demo):

$(window).on("keypress", function (e) {
    var t = e.which || e.keyCode;
    if (e.which === 0 && e.keyCode > 0 || e.altKey || e.ctrlKey || e.metaKey) {
        return;
    }
    var n = String.fromCharCode(t);
    $(".letter").find("span").html(n);
    e.preventDefault();
});
Sign up to request clarification or add additional context in comments.

1 Comment

i wanted to keep the alt functionality for sure so i left only ctrl and meta. works well! thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.