Press keys with javascript

События клавиатуры в JavaScript

При вводе с клавиатуры в javascript возникает сразу несколько событий, которые позволяют отследить коды нажатых клавиш и получить дополнительную полезную информацию для полного контроля над устройством ввода. Перейдём к теоретической и практической части.

События клавиатуры

В JS для клавиатуры используется 3 основных события:

  1. onkeydown — срабатывает при нажатии на клавишу и повторяется пока её не отжали.
  2. onkeypress — идентично предыдущему, но с 2 особенностями:
    • срабатывает после «onkeydown» и только для клавиш с символами;
    • функциональные клавиши, типа Alt и Ctrl , его не задействуют.
  3. 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».

Читайте также:  Java runtime execute environment

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 Keycode List – Keypress Event Key Codes for Enter, Space, Backspace, and More

TAPAS ADHIKARY

TAPAS ADHIKARY

JavaScript Keycode List – Keypress Event Key Codes for Enter, Space, Backspace, and More

JavaScript keyboard events help you capture user interactions with the keyboard.

Like many other JavaScript events, the KeyboardEvent interface provides all the required properties and methods for handling every keystroke a user makes using the keyboard.

There have been many articles written about how they work and how to use them. At the same time, W3.org keeps updating the specification by introducing new properties, deprecating existing ones, and marking certain code as legacy.

Because of this, it is essential for web developers to keep learning about the KeyboardEvent interface to know what exactly they should use and what's no longer relevant.

In this article, we will learn about:

  • The KeyboardEvent interface.
  • The keyboard event types we need to focus on.
  • The keyboard event types we may not ever need.
  • Which properties you need in practice and how different browsers handle them.
  • What is deprecated, and what's in use.
  • A playground to try things out as we learn.
  • Finally, the current list of key codes for reference and future use.

The KeyboardEvent interface and the event types

The KeyboardEvent interface provides information using the defined constants, properties, and a single method (as of January 2021). It extends the UIEvent interface which eventually extends the Event interface.

keyboardevent_hierarchy

There are primarily three keyboard event types, keydown , keypress and, keyup . We can get contextual information about these events from the KeyboardEvent interface's properties and methods.

You can add each of these event types to an HTML element or document object using the addEventListener method. Here is an example of listening to a keydown event on an element whose id is, 'type-here':

let elem = document.getElementById('type-here'); elem.addEventListener("keydown", function (event) < // The parameter event is of the type KeyboardEvent addRow(event); >);

Alternatively, you can use the handler methods like, onKeydown(event) , onKeyup(event) , onKeypress(event) with the element to handle keyboard events. Here is an example of handling a keyup event on an input element:

If you print the event object in the browser's console, you will see all its properties and methods along with the ones it inherits from the UIEvent and Event interfaces.

event_info

Try This Interactive Keyboard Event Playground

Before we go any further, how about a playground to explore all the keyboard events, their properties, characteristics, and so on? I think it will be awesome to use it alongside this article and beyond.

Just focus your cursor anywhere in the app embedded below, and type any key to see the contextual information about it.

You can also filter out the events you want by unchecking the checkboxes at the top. So give it a try:

Источник

Detect single and multiple keypress events: JavaScript

Detecting Keypress JavaScript

I used to just make websites and it made me completely ignorant to the importance of listening to keypress events in JavaScript. In truth, I didn’t ever have the need to handle multiple keypresses. Now that I have moved into app, gui and game development getting the keypresses right has become a lot more important.

The first thing I would like to say on the subject is not to use the ‘keypress’ event. This feature has been deprecated and gives you less control. I personally use ‘keydown’ and ‘keyup’ events instead.

Listening for a single key press

A ‘keydown’ event listener looks like this:

document.addEventListener('keydown', (event) => < // do something >);

When we use a ‘keydown’ event we are listening for the moment when a key is pressed. We can similarly react when a key is released using the ‘keyup’ event.

document.addEventListener('keyup', (event) => < // do something >);

Listening to elements for more specific focus

The above example is attached to the document. It is important to understand that where we attach the listener changes the behaviour. By attaching it to a more specific element we can localise key events and behaviours to when the element contains focus-within.

   

Notice that within the above example our ‘keydown’ event doesn’t fire when our focus is within the document, but does when we are in the input.

Checking which key has been pressed

At the moment our ‘do something’ code will fire on every key press. More commonly it is likely that we want to tie the ‘do something’ to a specific key press. This is why it is important to make the ‘event’ object available within our function. From within the ‘event’ object we can use ‘event.key’ to identify the specific key value that was pressed.

document.addEventListener('keyup', (event) => < if (event.key == 'ArrowUp') < // do something >>);

It is worth noting that when using ‘event.key’ we get the value of the key pressed. This means that when using a shift modifier the returned alphabetical character will be uppercase, or any modified character such as an @ symbol.

Listening for multi-key presses / creating modifiers

So what happens when we want to listen to 2 keys being pressed at the same time? Having a modifier key is quite a common scenario and used for the vast majority of keyboard shortcuts in applications.

The answer is to add an object to catch the key presses.

let keysPressed = <>; document.addEventListener('keydown', (event) => < keysPressed[event.key] = true; >);

When a key is pressed we add the value as the object key and set it to true. We now have a flag to tell us when certain key values are active. Next we make sure that we clear the key values when ‘keyup’ is triggered.

document.addEventListener('keyup', (event) => < delete this.keysPressed[event.key]; >);

Finally we can check for multiple keys with simple statements.

document.addEventListener('keydown', (event) => < keysPressed[event.key] = true; if (keysPressed['Control'] && event.key == 'a') < alert(event.key); >>); document.addEventListener('keyup', (event) => < delete keysPressed[event.key]; >);

Источник

Оцените статью