Эмуляция нажатия на клавиши с помощью простого кода javascript
Доброго времени суток, дорогие подписчики и гости блога. Сегодня я хочу разобрать с вами достаточно интересную и полезную тему: «JavaScript эмуляция нажатия клавиши».
Я расскажу вам, для чего и в каких случаях необходимо реализовывать имитацию нажатия на кнопки, представлю таблицу с наиболее популярными клавишами и их кодами, а также приведу примеры программного кода. Не буду больше тянуть с введением, давайте приступим к делу!
Имитация нажатия на кнопки клавиатуры? Но зачем!?
Если человек не сталкивается с определенной задачей, где необходимо реализовать что-то подобное, и при этом не имеет большого опыта веб-разработки, то ему достаточно сложно понять, зачем необходим рассматриваемый прием.
На самом деле эмуляцию нажатия реализуют достаточно часто. И вы не раз пользовались такими приемами на различных веб-сервисах. К примеру, у вас имеются какие-то поля для заполнения и определенная кнопка, которая их особым образом обрабатывает (не submit).
Вам нужно реализовать такую фичу, чтобы при нажатии пользователем на Enter вызывался обработчик вашей кнопки, т.е. происходила имитация нажатия на пользовательский элемент.
Другой пример. Вы пишите игру, в которой есть панель управления движением персонажа. Вам необходимо, чтобы при нажатии на стрелки клавиатуры (вверх, вниз, влево или вправо) срабатывали кнопки на панели, будто пользователь нажимает их в игровом поле.

Иногда такие приемы, к моему большому огорчению, используются хитрецами в спаме или других навязчивых всплывающих окнах.
Как пример можно привести такую ситуацию. Перед вами всплывает окно с рекламой, предлагающей переход на какой-то сомнительный ресурс. При этом по стандарту сверху справа находится кнопка закрытия. Однако по щелчку на спасительный крестик срабатывает переход на этот пакостный ресурс.
Это также иногда реализуется имитационным подходом: либо срабатывает не то событие, либо создается поверх рекламы большой прозрачный блок, который обрабатывается, как клавиша перехода.
Займемся расшифровкой кодов
В таблице представлены наиболее часто используемые кнопки. Если же для реализации поставленной задачи понадобятся коды других клавиш или символов, например, с кириллицы, то воспользуйтесь информацией с данного веб-сайта:
Время примерчиков
Ну а теперь пришло время показать вам пример реализации эмуляции нажатия на кнопку.
Итак, пользователю задается вопрос, ответ на который ему следует вписать в текстовое поле и после нажать на клавишу «Проверить». Щелчок и обработка события совершается двумя способами: либо при помощи клавиатуры, а точнее Enter-а, либо с помощью клика курсором мышки по кнопке.
Программная реализация приложения выглядит следующим образом:
Если данная публикация была вам полезна, то обязательно подписывайтесь на обновления блога. Здесь вы найдете еще много всего интересного и новенького. Буду благодарен за репосты моих статей с указанием ссылки на блог. До новых встреч! Пока-пока!
С уважением, Роман Чуешов

Да, хочу читать и Я
Simulate a Click With JavaScript

Simulating a click in JavaScript means that the click event will be automatically triggered on the HTML element without clicking it manually by the user. This simulated click functionality can come in handy in various situations while creating interactive web pages.
To implement the simulated click functionality, we can use a built-in click() functionality provided by the JavaScript programming language or create our own click event using the MouseEvent class.
Please enable JavaScript
Let’s see how to implement both of these ways in this article.
Simulate a Click Event Using click() in JavaScript
The click() method triggers a click event in JavaScript. This event is triggered without a user’s interaction.
The click() can be used with a supporting element, such as input . This method works based on a concept called Event bubbling.
In event bubbling, an event bubbles up to the higher elements in the document tree and then fires their click events whenever it is triggered.
In the below HTML document, we have an input tag, a checkbox, and a script tag that links the JavaScript file to the HTML document.
The input tag has an id of myCheck and an event called mouseover , which takes the function myFunction as an input.
The myFunction is defined inside the JavaScript file. Inside this function, we are getting the input tag that we have created using its id by the document.getElementById() function.
We then add the click() function to that input.
After executing this code on the browser, this is the output that you will get.
The drawback of this method is that it only works with some of the HTML elements. To learn more about the click() function, visit MDN docs.
However, if you want to simulate a click on links like an anchor <a> tag or something like that, you must write your function to simulate a click in JavaScript. The click() function will not work.
Implementing a Function to Simulate a Custom Click Event in JavaScript
To simulate a custom click event in JavaScript, we must implement our function. For this, we will use the MouseEvent API for adding the click event.
Before we create our function, let’s first create the HTML document. This HTML document will have an anchor tag and a link to the JavaScript file.
We have added an id of link on the anchor <a> tag to access this HTML element inside our JavaScript file. We also have named this tag Click Me (you can provide any name for this tag).
The HTML document looks like this.
To create a new mouse event in JavaScript, we must create an object of the MouseEvent class. The MouseEvent constructor takes two parameters typeArg and mouseEventInit .
The typeArg is the event’s name that it wants to create. In this case, it’s a click event.
The mouseEventInit is a dictionary that can take various parameters in itself, such as bubbles , view , clientX , metaKey , etc. To learn more about the MouseEvent constructor and the various parameters, please read its documentation at the MDN website.
bubbles : In event bubbling, the event will start executing from the innermost element and then up to its ancestors (parents). It takes a boolean value.
We have set it to false because we will be registering this event on a single element; the anchor tag. The element is also not present in a nested fashion.
cancelable : This tells the browser whether the event that we are executing can be canceled or not. It also takes a boolean value.
view : The MouseEvent also accepts view, which is a part of the UIEvent . It is set to null by default, but we can set its value to window as well.
This will execute the event inside the browser window.
The custom event created using the MouseEvent class will store inside the simulateClick variable.
To get the anchor tag inside our JavaScript file, we will use the document.getElementById method and pass the anchor tag, link , in the id. We will then store that element inside a variable called url .
Now that we have the reference to the anchor tag inside our JavaScript file and our custom click event is also ready, it’s time to add it to the anchor tag.
To fire up the simulated click event that we have created, we will use the dispatchEvent method on the url variable and then pass the simulateClick inside it as an argument.
To ensure that the simulateClick event that we have created is working correctly, we will add another click event on the url variable using addEventListener . Then we will console log a statement.
This line of code is to check whether the event we have created has been dispatched or not. It can be removed at any point.
This event should be added before executing our custom simulateClick event. Otherwise, you will not know whether the simulateClick event has been successfully executed or not.
The above code will produce the output below:
Conclusion
This article demonstrates two methods of simulating a click event in JavaScript. One way is by using a built-in function called click() , and another way is by creating and executing our custom click event simulateClick .
Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.
How to simulate a click with JavaScript?
I’m just wondering how I can use JavaScript to simulate a click on an element.
Currently I have:
But it’s not working 🙁
![]()
14 Answers 14
What about something simple like:
![]()
[Edit 2022] The answer was really outdated. Modernized it. The original answer is at the bottom.
Use element.dispatchEvent with a freshly created Event of the desired type.
Here’s an example using event delegation.
Fork this stackblitz project to play around with it.
The old answer:
Here’s what I cooked up. It’s pretty simple, but it works:
Have you considered using jQuery to avoid all the browser detection? With jQuery, it would be as simple as:
Reference
![]()
You could save yourself a bunch of space by using jQuery. You only need to use:
![]()
The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = ‘click’ .
So, I changed the document.createEvent to ‘MouseEvents’ and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.
![]()
![]()
In javascript grab element by its id or class name and then apply .click() to make click happens like:
Simulating an event is similar to creating a custom event. To simulate a mouse event
- we gonna have to create MouseEvent using document.createEvent() .
- Then using initMouseEvent() , we’ve to set up the mouse event that is going to occur.
- Then dispatched the mouse event on the element on which you’d like to simulate an event.
In the following code, I’ve used setTimeout so that the button gets clicked automatically after 1 second.
![]()
Follow this link to know about the mouse events using Javascript and browser compatibility for the same
![]()
![]()
Use timeout if the event is not getting triggered
Simply select the element from the DOM. The node has a click function, which you can call.
![]()
Honestly none of the answers here worked for my specific case. jquery was out of the question so all those answers are untested. I will say I built this answer up from @mnishiguchi answer above but this was the only thing that actually ended up working.
![]()
![]()
This isn’t very well documented, but we can trigger any kinds of events very simply.
Как имитировать клик по кнопке js
Что я/Вы подразумеваем под данным заголовком?
Требуется нажатием с клавиатуры активировать какую-то кнопку на сайте.
Предположим, что эта кнопка submit.
Вопрос : зачем это надо!?
Если вы часто работаете на сайте, а я часто работаю и много, и вообще все время!
И каждый раз отвлекать правую руку на мышку.
Потом искать кнопку на мониторе.
Опять же нажать. проходит 1-2 секунды, а то и больше.
Если вы делаете это один раз, то вам все равно, ну, а если как я. например 1000 раз таких отвлечений. это, как минимум 2000секунд = это примерно 30 минут. вы потратите только на то, что отвлекаетесь на мышку! это непростительная роскошь! Поэтому будем имитировать нажатие данной кнопки с клавиатуры!
Эмуляция нажатия кнопки js любой.
Не буду подробно разжевывать тему эмуляции, в том смысле о котором я говорил выше и плюс на сайте к моменту написания данных строк, как минимум три темы:
Начнем разбираться, как сделать эмуляцию нажатия кнопки
Для решения выше приведенного заголовка Вам потребуется:
Поставим один input с типом submit, в нем всегда непустой value.
Чтобы получить и вывести post запрос нам ещё понадобится атрибут name.
И чтобы эмулировать нажатие нам потребуется id.
Соберем форму: <form method="post">
<input type=submit value=сохранить name=save_edit ></form>
Php
Чтобы обработать эту форму, которую вы видели нам потребуется Php.
Сделаем простое условие(которое поместим на самый верх страницы), если массив $_POST(post) существует, то:
strip_tags — не забываем о безопасности.
if($_POST)
<
echo ‘здесь отправленный массив: <br>’.( strip_tags ( print_r ($_POST , true) )); exit;
>
Далее нам потребуется «javascript» с помощью которого будем эмулировать нажатие кнопки. Возьмем код из темы enter, заменим среднюю строку на код, который состоит из:
getElementById — обратимся к нашему , далее точка + click — без аргументов.