Interacting with Mouse, Keyboard, and More
Websites respond to keyboard and mouse actions by assigning functions to them.
You can accomplish this through HTML, like this: onkeypress="keypressFunction()"
,
onmousemove="mousemoveFunction()"
,
onclick="clickFunction()"
...
and various other events
<div onclick="clickFunction()">Clickable</div>
These functions such as keypressFunction()
, mousemoveFunction()
, clickFunction()
must be defined within your site, either inline
<script>
function clickFunction(){ alert('clicked!') }
</script>
or included from an external file:
<script src="myscripts.js"></script>
.
You can also attach event listeners using pure JavaScript:
//Use `document` instead of `element` to target the entire document
//Alternatively, locate elements by ID using document.getElementById('id')
//Various methods for locating elements are available, including querySelector or reusing existing variables
element.onkeypress = function(eventArgs){
eventArgs = eventArgs || window.event;
// Use eventArgs.keyCode to determine which key was pressed
};
Alternatively, a more common and secure method is to use addEventListener:
element.addEventListener('keypress', function(eventArgs){
eventArgs = eventArgs || window.event;
// Use eventArgs.keyCode to determine which key was pressed
});
Note that when utilizing addEventListener, you don't need to include the prefix on
in the event names (e.g., onkeypress
).
You can also assign pre-existing functions to events:
element.onkeypress = myFunction;
and
element.addEventListener('keypress', myFunction);
Most events provide event-specific parameters to offer detailed information about the event itself.
For instance, the onclick event provides arguments of type MouseEvent, allowing you to access data such as the mouse's coordinates (X and Y), whether modifier keys were held, and which mouse button was used.
Keyboard events come with their own set of event arguments, revealing details like the specific key pressed or if it's currently being held down. Further information on event arguments can be found here.
Simulating Events
Certain basic events, such as simulating a mouse click on an element, are achievable with simple commands like element.click();
. However, this method lacks control over the passed event arguments.
To accurately simulate an event, you need to create a browser event object and dispatch it onto an element:
//Triggering oncontextmenu (right-click) on an element:
var element = document.getElementById('Id_here');
if (window.CustomEvent) {
element.dispatchEvent(new CustomEvent('contextmenu'));
} else if (document.createEvent) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent('contextmenu', true, false);
element.dispatchEvent(ev);
} else { // For Internet Explorer
element.fireEvent('oncontextmenu');
}
With the event object in hand, you can pass additional data, such as simulating a keypress:
var element = document.getElementById('Id_here');
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown", // Event type: keydown, keyup, keypress
true, // Bubbles
true, // Cancelable
window, // View: Should be the window
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
65, // keyCode: Unsigned long - virtual key code, in this case, 65 for 'a'
0 // charCode: Unsigned long - Unicode character associated with the pressed key, otherwise 0
);
element.dispatchEvent(keyboardEvent);
JQuery offers convenient functions for simplifying event simulation, but resources can easily be found on Stack Overflow or Google. Look up phrases like js simulating keypress/mouse
, js subscribe to key/mouse event
, and explore various possibilities.