Key event in html

Element: keypress event

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The keypress event is fired when a key that produces a character value is pressed down.

Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don’t produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .

Warning: Since this event has been deprecated, you should use beforeinput or keydown instead.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("keypress", (event) => >); onkeypress = (event) => >; 

Event type

Event properties

This interface also inherits properties of its parents, UIEvent and Event . KeyboardEvent.altKey Read only Returns a boolean value that is true if the Alt ( Option or ⌥ on macOS) key was active when the key event was generated. KeyboardEvent.code Read only Returns a string with the code value of the physical key represented by the event.

Warning: This ignores the user’s keyboard layout, so that if the user presses the key at the «Y» position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return «KeyY», even if the user has a QWERTZ keyboard (which would mean the user expects a «Z» and all the other properties would indicate a «Z») or a Dvorak keyboard layout (where the user would expect an «F»). If you want to display the correct keystrokes to the user, you can use Keyboard.getLayoutMap() .

KeyboardEvent.ctrlKey Read only Returns a boolean value that is true if the Ctrl key was active when the key event was generated. KeyboardEvent.isComposing Read only Returns a boolean value that is true if the event is fired between after compositionstart and before compositionend . KeyboardEvent.key Read only Returns a string representing the key value of the key represented by the event. KeyboardEvent.locale Read only Returns a string representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn’t know the keyboard’s locale.

Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.

KeyboardEvent.location Read only Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown in Keyboard locations. KeyboardEvent.metaKey Read only Returns a boolean value that is true if the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key ( ⊞ )) was active when the key event was generated. KeyboardEvent.repeat Read only Returns a boolean value that is true if the key is being held down such that it is automatically repeating. KeyboardEvent.shiftKey Read only Returns a boolean value that is true if the Shift key was active when the key event was generated.

Examples

addEventListener keypress example

div> label for="sample">Focus the input and type something:label> input type="text" name="text" id="sample" /> div> p id="log">p> 
const log = document.getElementById("log"); const input = document.querySelector("input"); input.addEventListener("keypress", logKey); function logKey(e)  log.textContent += ` $e.code>`; > 

onkeypress equivalent

Источник

keydown и keyup

События происходят при нажатии клавиш клавиатуры. Но в чем между ними разница?

Время чтения: меньше 5 мин

Эта статья связана с обработкой событий в JavaScript. Зачем нужны события и как с ними работать читайте в статье События.

Кратко

События на HTML-элементе. Когда пользователь нажимает на клавишу клавиатуры, происходит событие keydown , как только пользователь отпустил клавишу — произойдёт событие keyup .

Событие keydown фиксирует момент нажатия клавиши, до того как эта клавиша будет отпущена, что, по сути, является первой фазой нажатия. Продолжением является событие keyup — момент, когда клавиша будет отпущена.

Как пишется

keydown

 const spy = document.getElementById('keyboardSpy') spy.addEventListener('keydown', function (event)  alert('Нажата клавиша ' + event.key)>) const spy = document.getElementById('keyboardSpy') spy.addEventListener('keydown', function (event)  alert('Нажата клавиша ' + event.key) >)      

keyup

 const spy = document.getElementById('keyboardSpy') spy.addEventListener('keyup', function (event)  alert(`Клавиша $ отпущена`)>) const spy = document.getElementById('keyboardSpy') spy.addEventListener('keyup', function (event)  alert(`Клавиша $event.key> отпущена`) >)      

Как понять

В функцию-обработчик также передаётся объект события, в котором есть информация о нажатой кнопке:

  • key — символьное значение. s , Я , U и так далее.
  • code — название клавиши. KeyS , KeyZ , KeyU и так далее.
  • altKey — true или false , была ли одновременно нажата/отпущена клавиша Alt .
  • ctrlKey — true или false , была ли одновременно нажата/отпущена клавиша Ctrl .
  • shiftKey — true или false , была ли одновременно нажата/отпущена клавиша Shift .
  • metaKey — true или false , была ли одновременно нажата/отпущена так называемая мета-клавиша (на Mac клавиатурах это ⌘ Command , а в Windows клавиатурах — Windows key ⊞ ).
  • keyCode — код нажатой клавиши. 83 , 90 , 85 и так далее.

️Свойство keyCode является устаревшим! Избегайте его использования, поскольку его поддержка может быть прекращена браузерами в будущем.

key возвращает символьное представление клавиши. Другими словами, если эта клавиша печатает какой-то символ, то key будет содержать его. В случае, если нажата управляющая клавиша (Shift, Ctrl и т.д.), key вернёт название этой клавиши.

code же возвращает название клавиши в контексте её физического положения на клавиатуре. Например, если взять стандартную русско-английскую QWERTY клавиатуру и нажать в русской раскладке q / й , key будет q , а code — KeyQ . Если переключить раскладку на английский и нажать ту же клавишу, то key поменяется на й , а вот code так и останется KeyQ . Также code даёт больше информации положении парных клавиш. Если нажать левый Shift, то key будет содержать просто Shift , зато code вернёт — ShiftLeft .

Благодаря этим свойствам, code удобно использовать, например для управления клавиатурой в играх, когда есть необходимость задать определённым клавишам нужные действия независимо от языка раскладки.

Если подытожить, то key говорит нам, какой символ будет напечатан, а code — название этой клавиши на клавиатуре независимо от текущего языка ввода.

Пример Keydown

При нажатии на любую клавишу в демо ниже, будет срабатывать событие keydown , которое будет выводить подсказку о нажатых клавишах:

Пример Keyup

Следующее демо будет сохранять цвет до тех пор, пока не будет зафиксировано событие keyup на клавише Shift .

Событие keydown выполняется бесконечное множество раз, до тех пор, пока клавиша будет зажата. Событие keyup будет выполнено только один раз — в момент, когда пользователь отпустит клавишу

На практике

Алекс Стегура

🛠 События помогут добавить горячие клавиши на сайт. Например, открывать меню по комбинации клавиш или скрывать окна по кнопке Esc .

🛠 Существует похожее событие keypress , оно устаревшее. Вместо него нужно использовать keydown .

Источник

Element: keyup event

The keyup event is fired when a key is released.

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase «a» will be reported as 65 by keydown and keyup , but as 97 by keypress . An uppercase «A» is reported as 65 by all events.

Keyboard events are only generated by , , and anything with the contentEditable or tabindex attribute.

Since Firefox 65, the keyup and keydown events are now fired during IME composition, to improve cross-browser compatibility for CJKT users (Firefox bug 354358. To ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keyCode relating to an event that has been processed by an input-method editor (IME)):

.addEventListener("keyup", (event) =>  if (event.isComposing || event.keyCode === 229)  return; > // do something >); 

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("keyup", (event) => >); onkeyup = (event) => >; 

Event type

Event properties

This interface also inherits properties of its parents, UIEvent and Event . KeyboardEvent.altKey Read only Returns a boolean value that is true if the Alt ( Option or ⌥ on macOS) key was active when the key event was generated. KeyboardEvent.code Read only Returns a string with the code value of the physical key represented by the event.

Warning: This ignores the user’s keyboard layout, so that if the user presses the key at the «Y» position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return «KeyY», even if the user has a QWERTZ keyboard (which would mean the user expects a «Z» and all the other properties would indicate a «Z») or a Dvorak keyboard layout (where the user would expect an «F»). If you want to display the correct keystrokes to the user, you can use Keyboard.getLayoutMap() .

KeyboardEvent.ctrlKey Read only Returns a boolean value that is true if the Ctrl key was active when the key event was generated. KeyboardEvent.isComposing Read only Returns a boolean value that is true if the event is fired between after compositionstart and before compositionend . KeyboardEvent.key Read only Returns a string representing the key value of the key represented by the event. KeyboardEvent.locale Read only Returns a string representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn’t know the keyboard’s locale.

Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.

KeyboardEvent.location Read only Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown in Keyboard locations. KeyboardEvent.metaKey Read only Returns a boolean value that is true if the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key ( ⊞ )) was active when the key event was generated. KeyboardEvent.repeat Read only Returns a boolean value that is true if the key is being held down such that it is automatically repeating. KeyboardEvent.shiftKey Read only Returns a boolean value that is true if the Shift key was active when the key event was generated.

Examples

addEventListener keyup example

input placeholder="Click here, then press and release a key." size="40" /> p id="log">p> 
const input = document.querySelector("input"); const log = document.getElementById("log"); input.addEventListener("keyup", logKey); function logKey(e)  log.textContent += ` $e.code>`; > 

onkeyup equivalent

Источник

Читайте также:  Как правильно использовать javascript
Оцените статью