I try to prevent the default zoom event and trigger a function instead.
I managed to do it for the default save event (CTRL+S) across browsers:
document.documentElement.addEventListener('keydown', function(e) {
e = e || window.event;
var keynum;
if (window.event) {
keynum = e.keyCode;
} else if (e.which) {
keynum = e.which;
if (e.ctrlKey) {
switch (String.fromCharCode(keynum)) {
case 'S':
console.log('CTRL S pressed');
e.preventDefault ? e.preventDefault() : (e.returnValue = false);
break;
}
}
}
});
https://codepen.io/anon/pen/NjRbaa?editors=1010
However, CTRL++ seems more tricky since there is no cross browser keyCode for the "+" sign. I tried to use keypress instead of keydown but then the default isn't prevented in Chrome and IE.
https://github.com/jeresig/jquery.hotkeys Try this :)
$(document).on('keydown', null, 'ctrl+s', fn);
I want to prevent the default event on key #93 (select, between alt gr and ctrl right on AZERTY keyboard).
This key open context menu like right click.
I tried :
$(document).off('keydown');
$(document).off('keyup');
$(document).off('keypress');
$(document).on('keypress', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keyup', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keydown', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
Nothing works... I have always the contextmenu.
After checking for a while, I've been headed to another question similar to this one, but with a very different matter.
In any case, since the problem is the context menu, you don't even need jQuery for such, and the solution (despite it WON'T always work in firefox because the user may set it to disable such) is this one:
document.oncontextmenu = function (e) {
e.preventDefault();
return false;
}
fiddle:
http://jsfiddle.net/0kkm1vq0/3/
Works on chrome as well, and you won't need to use the keyboard listeners.
Reference: How to disable right-click context-menu in javascript
(which is really the same as key #93).
** note that this will disable the right click too **.
EDIT:
Not sure if this is cross-browser (the UPDATED code below seems to be working for both chrome and firefox, didn't try IE and others though), but the event fired by key #97 seems to be identified as 1, while the click seems to be identified as key 3, so you can just:
(function($){
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
$(document).on('keyup', function(e) {
e.which == 93 && e.preventDefault();
});
}
else {
document.oncontextmenu = function (e) {
e.which == 1 && e.preventDefault();
}
}
})(jQuery);
http://jsfiddle.net/0kkm1vq0/10/
To disable JUST the key and not the right click.
I am trying to implement a keyboard shortcut for my application. I want to use ALT + Q combination. However, when I try to run the code and press ALT key, it sets focus on the browsers menu bar control and it fails.
I tried to stop event propagation by several methods like,
function KeyDownEventHandler() {
if (event.keyCode == 18) {
//stop code
}
}
stopPropagation(event);
CancleBubbling();
return false;
event.preventDefault();
Still it behaves the way.
EDIT - Actually the problem is not with detection. When user press ALT key and release it and Q key is pressed after that, it highlights browser menu. It doesn't call function for custom shortcut.
Is it the default behaviour of the browser ? Can we override it ?
Please help in the same.
Thanks
UPDATE
Here is a fiddle detecting exactly "ALT+Q" sequence:
document.onkeydown = KeyCheck;
var previousKeyCode = 0;
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch (KeyID)
{
case 18:
previousKeyCode = 18;
break;
case 81:
if (previousKeyCode == 18) {
alert("ALT+Q Pressed!!!")
}
previousKeyCode=KeyID;
break;
default: previousKeyCode=KeyID;
}
}
I'm making a game using canvas, and javascript.
When the page is longer than the screen (comments, etc.) pressing the down arrow scrolls the page down, and makes the game impossible to play.
What can I do to prevent the window from scrolling when the player just wants to move down?
I guess with Java games, and such, this is not a problem, as long as the user clicks on the game.
I tried the solution from: How to disable page scrolling in FF with arrow keys ,but I couldn't get it to work.
Summary
Simply prevent the default browser action:
window.addEventListener("keydown", function(e) {
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);
If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated and you need to use actual codes instead of strings:
// Deprecated code!
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
Original answer
I used the following function in my own game:
var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.code] = true;
switch(e.code){
case "ArrowUp": case "ArrowDown": case "ArrowLeft": case "ArrowRight":
case "Space": e.preventDefault(); break;
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.code] = false;
},
false);
The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.
If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:
var arrow_keys_handler = function(e) {
switch(e.code){
case "ArrowUp": case "ArrowDown": case "ArrowLeft": case "ArrowRight":
case "Space": e.preventDefault(); break;
default: break; // do not block other keys
}
};
window.addEventListener("keydown", arrow_keys_handler, false);
Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:
window.removeEventListener("keydown", arrow_keys_handler, false);
References
MDN: window.addEventListener
MDN: window.removeEventListener
MDN: KeyboardEvent.code interface
For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).
theCanvas.onkeydown = function (e) {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.view.event.preventDefault();
}
}
Why not simply do window.event.preventDefault()? MDN states:
window.event is a proprietary Microsoft Internet Explorer property
which is only available while a DOM event handler is being called. Its
value is the Event object currently being handled.
Further readings:
https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false} property for window.addEventListener, which is recommended as the only working solution, for example here.
In the end, after many tries, I found a way that works for me in both Firefox and Chrome:
window.addEventListener('keydown', (e) => {
if (e.target.localName != 'input') { // if you need to filter <input> elements
switch (e.keyCode) {
case 37: // left
case 39: // right
e.preventDefault();
break;
case 38: // up
case 40: // down
e.preventDefault();
break;
default:
break;
}
}
}, {
capture: true, // this disables arrow key scrolling in modern Chrome
passive: false // this is optional, my code works without it
});
Quote for EventTarget.addEventListener() from MDN
options Optional
An options object specifies characteristics about the event listener. The available options are:
capture
A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
once
...
passive
A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. ...
This is the accepted answer rewritten for React.
import { useEffect } from "react";
const usePreventKeyboardScrolling = () => {
const onKeyDown = (e) => {
if (
["Space", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].indexOf(
e.code
) > -1
) {
e.preventDefault();
}
};
useEffect(() => {
window.addEventListener("keydown", onKeyDown, false);
return () => window.removeEventListener("keydown", onKeyDown);
});
};
export { usePreventKeyboardScrolling };
I'd like to add support for keyboard shortcuts to a couple of pages in my web application by intercepting the keypress event handler of the document object, not the accesskey attribute.
The problem is that every browser has its own keyboard combinations, so it's impossible to come up with a set of keyboard combinations that work on all web browsers and yet consistent.(e.g. It'd be silly if the shortcut for save was Ctrl + Shift + S while one for delete was Alt + D.)
So I figured it would be just simpler to override browser shortcuts altogether in a couple of pages with mine.
All downside aside, is it possible? If so, how do you do it?
onkeydown = function(e){
if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
e.preventDefault();
//your saving code
}
}
There's an excellent coverage of this here: http://unixpapa.com/js/key.html
As for whether this is something that should be done, stackoverflow's question editor override's quite a few keys without disrupting too much (hover over the toolbar buttons).
Here is my solution to this problem:
Most (if not all) of the browser's shortcuts will be overriden. Only system ones, like Alt + Tab or the Windows key won't.
document.onkeydown = overrideKeyboardEvent;
document.onkeyup = overrideKeyboardEvent;
var keyIsDown = {};
function overrideKeyboardEvent(e){
switch(e.type){
case "keydown":
if(!keyIsDown[e.keyCode]){
keyIsDown[e.keyCode] = true;
// do key down stuff here
}
break;
case "keyup":
delete(keyIsDown[e.keyCode]);
// do key up stuff here
break;
}
disabledEventPropagation(e);
e.preventDefault();
return false;
}
function disabledEventPropagation(e){
if(e){
if(e.stopPropagation){
e.stopPropagation();
} else if(window.event){
window.event.cancelBubble = true;
}
}
}
Here is my Solution:
document.onkeydown = function () {
if ((window.event.keyCode == 121) && (window.event.ctrlKey))) {
window.event.returnValue = false;
window.event.cancelBubble = true;
window.event.keyCode = 0;
return false;
}
}