Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to add keyboard shortcuts javascript

document.addEventListener("keydown", (event) => {
	/*
		event.key returns the character being pressed
        event.preventDefault() prevents the default browser behavior for that shortcut, e.g. ctrl+r usually reloads the page, but event.preventDefault() will turn off that behavior. event.preventDefault() should only be used if you share a shortcut with the same trigger as the browser.
        event.ctrlKey / event.altKey / event.shiftKey / event.metaKey all return booleans. They will be true when they are being pressed, otherwise they will be false.
	*/
	if (event.ctrlKey && event.key.toLowerCase() === "d") {
    	//Do something
	} else if (event.ctrlKey && event.key.toLowerCase() === "p") {
    	//Do something else
	}
});	
 
PREVIOUS NEXT
Tagged: #add #keyboard #shortcuts #javascript
ADD COMMENT
Topic
Name
8+4 =