- События клавиатуры в JavaScript
- События клавиатуры
- Получение свойств событий
- Свойства key и keyCode
- Свойства code и charCode
- Свойства altKey, ctrlKey, shiftKey
- Проверка зажатой клавиши Command на Mac
- Свойство type
- Свойство repeat
- Пример проверки ввода в Input
- Коды клавиш
- JavaScript Onkeypress Event
- Syntax of JavaScript onkeypress Event
- Return Value of JavaScript onkeypress Event
- Exceptions of JavaScript onkeypress Event
- Example
- How does JavaScript onkeypress Event Work?
- Technical Details
- More Examples
- Supported Browser
- Conclusion
- onkeypress Event
- Keyboard Events
- See Also:
- Warning
- Syntax
- Technical Details
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
События клавиатуры в JavaScript
При вводе с клавиатуры в javascript возникает сразу несколько событий, которые позволяют отследить коды нажатых клавиш и получить дополнительную полезную информацию для полного контроля над устройством ввода. Перейдём к теоретической и практической части.
События клавиатуры
В JS для клавиатуры используется 3 основных события:
- onkeydown — срабатывает при нажатии на клавишу и повторяется пока её не отжали.
- onkeypress — идентично предыдущему, но с 2 особенностями:
- срабатывает после «onkeydown» и только для клавиш с символами;
- функциональные клавиши, типа Alt и Ctrl , его не задействуют.
- onkeyup — срабатывает один раз после отжатия.
document.addEventListener('keydown', function()< console.log('Success onkeydown'); >);
document.addEventListener('keypress', function()< console.log('Success onkeypress'); >);
document.addEventListener('keyup', function()< console.log('Success onkeyup'); >);
Для избежания повторных вызовов «keydown» и «keypress» используйте свойство «repeat». Подробнее рассмотрим его позже.
В примерах использовался метод «addEventListener», но можно встретить и другие варианты:
// устаревший способ document.onkeydown = function()< console.log('Success onkeydown'); >);
// на jQuery $(document).on('keydown', function()< console.log('Success onkeydown'); >);
Получение свойств событий
Для получения информации о клавише обратитесь к свойствам объекта «event».
document.addEventListener('keyup', function(event)< console.log('Key: ', event.key); console.log('keyCode: ', event.keyCode); >);
Свойства key и keyCode
key — возвращает значение нажатой клавиши в виде строки. Например, «F», «5» или «Enter».
keyCode — возвращает числовой код. Для события «keypress» вернёт ASCII-код нажатого символа.
Примечание. Цифры на верхнем и боковом блоке клавиатуры имеют разные «keyCode».
Коды основных функциональных клавиш:
Клавиша | Key | keyCode |
---|---|---|
Ввод | Enter | 13 |
Стереть | Backspace | 8 |
Удалить | Delete | 46 |
Пробел | Space | 32 |
Табулятор | Tab | 9 |
Esc | Escape | 27 |
Стрелка влево | ArrowLeft | 37 |
Стрелка вверх | ArrowUp | 38 |
Стрелка вправо | ArrowRight | 39 |
Стрелка вниз | ArrowDown | 40 |
Shift | Shift | 16 |
Ctrl | Control | 17 |
Alt | Alt | 18 |
Хорошей практикой в JavaScript считается использование «key», а не «keyCode». Это повышает читаемость кода и избавляет от необходимости запоминать соответствие кодов их значениям.
Свойства code и charCode
Актуальны только для события «keypress».
- code — возвращает строковое наименование символа. Для букв имеет вид «keyD», «keyF». Такие значения будут возвращены независимо от установленного языка и регистра букв. Для цифр верхнего блока клавиатуры возвращает значение вида «Digit5», для бокового — «Numpad5».
- charCode — возвращает код символа из таблицы ASCII. Код букв на разных языковых раскладках клавиатуры отличается. Регистр также имеет значение. Например, » f » имеет код 102, а » F » — 70.
document.addEventListener('keypress', function(event)< console.log('Строковый код: ', event.code); console.log('ASCII код: ', event.charCode); >);
Не поддерживаются IE и старыми версиями других браузеров.
Свойства altKey, ctrlKey, shiftKey
Позволяют отследить, зажат ли в момент события Alt , Ctrl или Shift . Удобно использовать для создания горячих клавиш.
document.addEventListener('keydown', function(event) < if (event.shiftKey && ['F','f'].includes(event.key) ) < console.log('Нажаты Shift + F или Shift + f'); >>);
Проверка зажатой клавиши Command на Mac
На устройствах компании Apple в горячих клавишах вместо Ctrl часто используют Cmd . Чтобы разграничить их действие для Mac и остальных устройств применяйте конструкцию с проверкой свойства «metaKey».
document.addEventListener('keydown', function(event)< const isCtrlCmd = window.navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey; if (isCtrlCmd && event.key == '+') console.log('Ctrl/Cmd +'); if (isCtrlCmd && event.key == '-') console.log('Ctrl/Cmd -'); >);
Свойство type
Возвращает тип события в виде строки. Может использоваться, когда один обработчик применяется сразу для нескольких событий.
['keydown', 'keyup'].forEach(function(event) < window.addEventListener(event, function(event)< if (event.type == 'keydown') < console.log('Зажали. '); >else if (event.type == 'keyup') < console.log('Отжали'); >>); >);
Свойство repeat
Возвращает логическое «true», если событие уже один раз отработало и автоматически вызывается снова. Подобная ситуация возникает при зажатии клавиши на длительное время — «keydown» и «keypress» начинают срабатывать повторно.
document.addEventListener('keydown', function(event) < if (event.repeat == false) < console.log('первичное срабатывание'); >else < console.log('повторное срабатывание'); >>);
Пример проверки ввода в Input
Рассмотрим небольшой пример, в котором разрешим ввод в текстовое поле только нуля и единицы. Учитываем возможность стирания, удаления и табуляции.
// HTML // SCRIPT document.getElementById('binaryInput').addEventListener('keydown', function(event) < if (!['0','1','Backspace','Delete','Tab'].includes(event.key)) < event.preventDefault(); >>);
Метод «preventDefault()» запрещает действие по умолчанию.
Применение предыдущего обработчика ко всем текстовыми полями на странице:
document.querySelectorAll('input[type="text"]').forEach(function(element) < element.addEventListener('keydown', function(event)< if (!['0','1','Backspace','Delete','Tab'].includes(event.key)) < event.preventDefault(); >>); >);
Коды клавиш
Поставьте курсор в поле ввода и нажмите любую клавишу:
Добрый день.
Нашел два скрипта на JS которые выполняют нужные мне функции. Первый скрипт задает числа в секундах при нажатии кнопок и сумирует выдавая результат и публикует его в поле > Второй скрипт должен брать число из поля и переводит его в часы и дни выдавая результат в поле автоматически сразу как там появляется число. Но проблема в том что второй скрипт срабатывает если в поле вводить число в ручную с клавиатуры либо нажать клавишу «ENTER» если же в поле появляется число которое публикует первый скрипт при нажатии кнопки тогда второй скрипт не срабатывает. Как автоматизировать процесс чтобы при нажатии даже одной кнопки из первого скрипта появлялся конечный результат в днях и часах в поле из второго скрипта.
Например как дописать в первый скрипт функцию которая имитирует нажатие клавиши «INTER» после того как число публикуется в поле с > Идеальный вариант это убрать поле а число которое должно публиковаться в поле с чтобы передавалось сразу во второй скрипт который переводит его в дни и часы сразу выдавая результат.
Добрый день.
Вызывай в конце функции addition(), которая срабатывает каждый раз при нажатии на кнопку, функцию her(res); для пересчета значения.
Но честно говоря, весь код очень плох. Так не программируют.
JavaScript Onkeypress Event
"onkeypress" event is one of the three keyboard events that we can use in JavaScript. There are three keyboard events in JavaScript named- onkeydown, onkeypress, and onkeyup. The onkeypress JavaScript is a event that triggers when the user presses a key (on the keyboard) to the function to which it is attached.
Syntax of JavaScript onkeypress Event
Syntax of the onkeypress javascript is as follows:
For HTML, the syntax will be like this:
For JavaScript, the syntax will be like this:
Syntax of onkeypress event using addEventListener() method in JavaScript:
Return Value of JavaScript onkeypress Event
The return value of onkeypress javascript is the activity that we do with our keyboard. It returns the keyboard events such as pressing input keys (like alphanumeric and numeric keys) as its only parameter.
Exceptions of JavaScript onkeypress Event
There are some exceptions to onkeypress javascript event that we need to keep in mind while using this event in our code.
- There are some keys in our keyboard that does not triggers the onkeypress event in all browsers. For example- ALT, CTRL, SHIFT, and ESC.
- If you want to check whether any of the keys from keyboard is pressed, you can use the "onkeydown" event because it is supported for all categories of keys.
- In Internet Explorer, this event is only supported after version 8.
Example
Let us see an example for a better understanding of onkeypress javascript event.
- When the key is pressed, the "onkeypress" event will be triggered and a pop-up dialog box will appear like this:
How does JavaScript onkeypress Event Work?
The onkeypress javascript event in JavaScript is used to detect any key activity from the keyboard. The event gets triggered when a key is pressed from the keyboard. But the trigger does not happen for every key of the keyboard. JavaScript onkeypress event only works for the keys that are used to print or type something (alphanumeric and number keys). We create a function inside the 'script' element of HTML for performing the event. This function is called when the user types anything in the text field area where the event is attached with.
Technical Details
There are some technicalities that we need to know about the onkeypress JavaScript which is as follows:
Note: Bubbling is an event where the elements run from the inner most element to outer most element
Note: Cancelable is an event that returns a boolean vaue (true or false) for an event whether it is cancealable or not.
Note: Dom(Docment Object Model) is an API for HTML and XML documents that defined the logical structure of the document.
More Examples
Let us cover more examples to understand the onkeypress javascript event in detail.
Example 1: Given below is an example to check the unicode of a character entered by the user.
Example 2: In the given example , we used onkeypress event to restrict the user to input any numeric value in the text field.
The given text field will not accept any value if you enter a numeric value in it.
Supported Browser
Following are the name of the browser that supports "onkeypress event" in Javascript.
Browser Name | Supported on versions |
---|---|
Internet Explorer | version >= 7(Aug 2001) |
Mozilla Firefox | version >= 2(Oct 2006) |
Microsoft Edge | version >= 12(Jul 2015) |
Google Chrome | version >= 4(Jan 2010) |
Safari | version >= 3.1(Mar 2008) |
Opera | version >= 9.5 |
Conclusion
- onkeypress javascript is an event that gets triggered when the user hits keys from the keyboard.
- onkeypress javascript in JavaScript does not get triggered for some keys that are ALT, CTRL, SHIFT, and ESC.
- onkeypress event in JavaScript gets triggered just by the time a user enters any value on the keyboard.
- You can also use "addEventListener()" method to use onkeypress event in JavaScript but this method is not supported in earlier versions of Internet Explorer 8.
- Some famous browser that supports the onkeypress javascript event are Chrome, Safari, Internet Explorer, etc.
onkeypress Event
The onkeypress event occurs when the user presses a key on the keyboard.
Keyboard Events
See Also:
Warning
The onkeypress event is deprecated.
It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all browsers.
To detect if the user presses a key, always use the onkeydown event. It works for all keys.
Syntax
In JavaScript, using the addEventListener() method:
Technical Details
Bubbles: | Yes |
---|---|
Cancelable: | Yes |
Event type: | KeyboardEvent |
HTML tags: | All HTML elements, EXCEPT: , , , , , , , , , , and |
DOM Version: | Level 2 Events |
Browser Support
onkeypress is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.