Simulate Mouse Click Using JavaScript: Nowadays simulating processes is common between programmers to avoid doing tasks on their own and it is obvious why they do it on their own when they can simulate that process which will work for them whenever they want, program once and use for lifetime :).
You can also simulate the process using JavaScript. In this article, we’ll look at how we can simulate a mouse click with JavaScript.
So the question arises that how can we simulate it with JavaScript, so basically we are going to use MouseEvent constructor of JavaScript, if you don’t know what MouseEvent does you’ll see that in action in this article.
What is MouseEvent In JavaScript?
The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click, dblclick, mouseup, mousedown.
Learn more about MouseEvent.
MouseEvent constructor supports multiple browser compatibility, so you can use this for any browser you want.
MouseEvent Constructor in Action
Lets trigger a mouse click event by using the MouseEvent constructor.
Below is the code paste the following code in your browser console for testing:
document.body.addEventListener('click', () => { name = prompt("Enter you name"); console.log(name); }); const simulate = new MouseEvent('click', { view: window, bubbles: true, cancelable: true, clientX: 100, }); document.body.dispatchEvent(simulate);
Let’s break the code line by line for better understanding what is happening here.
We added a click event on document.body with the addEventListener method and inside our callback function we’re calling prompt function and then printing the name variable.
Then we called the MouseEvent function and passed the first argument as a click as the first argument to set the type of mouse event.
The 2nd argument we passed is an object that sets some properties to make the mouse event work.
view is set to window so that we can trigger the click event on an element within the window.
bubbles are set to true to make it propagate from the child parent.
clientX is the x-coordinate of the mouse click on the document.
Then we are calling document.body.dispatchEvent to trigger the click event on the body element.
Now when dispatch is run, we will see a prompt appear in the window and ask for your name and when you feed your name in prompt and hit enter you’ll see your name appear in the console.
your comments are appreciated and if you wants to see your articles on this platform then please shoot a mail at this address kusingh@programmingeeksclub.com
Thanks for reading 🙂