LoginSignup
59
56

More than 5 years have passed since last update.

DOM Keyboardイベントで押されたキーを判別するにはkeyプロパティを使う

Last updated at Posted at 2015-07-16

エンターキー押下に反応するインタラクションを作りたいときなど、押されたキーを検出する話です。
入力文字列を検出する時はinputイベントを使います。

keyプロパティが推奨

keyプロパティがあります。

window.document.onkeydown = function(event){
    if (event.key === 'Enter') console.log('hello Enter')
}

詳しい仕様は以下を見てください。

主要なブラウザでサポート

KeyboardEvent.key - Web APIs | MDN
によるとと、2017/8/14日時点で

  • Chrome
  • Edge
  • Firefox (Gecko)
  • Internet Explorer
  • Opera
  • Safari (WebKit)

でサポートされています。

polyfill

IE8や古いAndroidのブラウザをサポートしたい場合、keyプロパティを提供するpolyfillライブラリが存在します。

後者の方がbowerパッケージがあるので多少使いやすいかもしれません。

keycodeは非推奨

KeyboardEvent.keyCode - Web API Interfaces | MDNによれば、keycodeプロパティは非推奨です。

Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

伝統的な次のソースコードは、これからは時代遅れになりつつあるようです。

window.document.onkeydown = function(event){
    if (event.keyCode === 13) console.log('hello Enter')
}

keyIdentifierは過去のプロパティ

ChromeとSafariにはkeyIdentifierというプロパティがありました。
使い方はkeyプロパティに似ています。

window.document.onkeydown = function(event){
    if (event.keyIdentifier === 'Enter') console.log('hello Enter')
}

残念ながら現在のWeb標準からは消えています。
詳しくは以下を見てください。

まとめ

主要なブラウザでkeyプロパティがサポートされています。
どんどん使っていきましょう!

59
56
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
59
56