JS bind a keyboard shortcut to a function - javascript

function initKeys() {
$(document).bind("keydown", "U", LoadPlayer);
}
window.onload = initKeys;
I want to execute the function 'LoadPlayer' on pressing the u key.
What I'm getting is that for any pressed key the 'LoadPlayer' is executed.
The HotKeys library is added like this:
<script language="javascript" type="text/javascript" src="./libraries/jquery.hotkeys.js"></script>
But it cannot be found. I've putted it in the exact same place as other libraries. No problem with other ones
What am I doing wrong?

Try this, it should work.
It checks the key pressed in an anonymous function (so that you can add as many hotkeys as you need).
$(document).ready(function(){
$(document).bind("keydown", function(e){
e = e || window.event;
var charCode = e.which || e.keyCode;
if(charCode == 85) LoadPlayer();
});
});
Demo: http://jsfiddle.net/HULgw/
(click in the result block after running to make the keydown event listened :) )

You're binding the keydown event on all keys. that "U" is the parameter you will pass to the handler, loadPlayer (q.v http://api.jquery.com/bind/). Instead bind keydown directly, and filter inside it on the keycode.

Try deleting ./ from your javascript src path. Also check file permissions on your hotkeys library.

Related

Detecting ctrl + arrow keys in javascript [duplicate]

I see some similar questions here (like JavaScript: Check if CTRL button was pressed) but my problem is actually the event triggering. My js code:
// Listen to keyboard.
window.onkeypress = listenToTheKey;
window.onkeyup = listenToKeyUp;
/*
Gets the key pressed and send a request to the associated function
#input key
*/
function listenToTheKey(e)
{
if (editFlag == 0)
{
// If delete key is pressed calls delete
if (e.keyCode == 46)
deleteNode();
// If insert key is pressed calls add blank
if (e.keyCode == 45)
createBlank();
if (e.keyCode == 17)
ctrlFlag = 1;
}
}
The event triggers for any other keys except the ctrl.
I need to also trigger it for ctrl.
I can't use jQuery/prototype/whatever so those solutions are not acceptable.
So... how can I detect the ctrl?
Try using if (e.ctrlKey).
MDN: event.ctrlKey
Using onkeydown rather than onkeypress may help.
From http://www.w3schools.com/jsref/event_onkeypress.asp
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL,
SHIFT, ESC) in all browsers. To detect only whether the user has
pressed a key, use the onkeydown event instead, because it works for
all keys.
Your event has a property named ctrlKey. You can check this to look if the key was pressed or not. See snippet below for more control like keys.
function detectspecialkeys(e){
var evtobj=window.event? event : e
if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectspecialkeys
This is basically Rick Hoving's answer, but it uses keydown like Danielle Cerisier suggests
function detectspecialkeys(e) {
var evtobj = window.event ? event : e
if (evtobj.ctrlKey)
console.log("You pressed ctrl")
}
document.onkeydown = detectspecialkeys
Please note that you may have to click inside the preview box to focus before pressing ctrl

Switch jQuery onClick to keyCode

What am I missing in order to translate my jQuery onClick events into keypress events where a user can use a keypad?
The specific example is for a calculator. Using jQuery and the on click/touch events work perfect. However, when I try to introduce keyCodes I am not getting the results I think I should.
Here is my example code;
$(document).keypress(function(event){
var display = "0";
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode === 13){
alert(keycode + " = ENTER");
calcDisplay(total(), true);
}
});
Most of this I picked up from other successful solutions to similar issues. So the way I understand it is; if someone presses "enter" on the keyboard, I'd get my alert and then process my answer.
The jQuery version of this that works for me looks like this;
$(".button").on("click touch", function(){
var button = $(this).data("value");
if(button === "="){
calcDisplay(total(), true);
}
superNewb to JS here so much love ahead of time if this is something super foolish on my end.
keypress is meant to be used when characters are being inserted as input. keydown is meant to be used to detect any key.
quirksmode has a nice little write-up about the differences.
Instead of $(document).keypress use $(document).keydown.
Additionally, jQuery normalizes event.which, so instead of:
var keycode = (event.keyCode ? event.keyCode : event.which);
you can use
var key = e.which;

Handling events for mouse click and keydown or keypress (for non-modifier keys)

I am new to JS and trying to learn on my own - thanks for any help!
I am trying to have a simple program respond to a click differently depending on what other key is pressed at the time of the mouse click.
I have searched far and wide and have not been able to find an answer that works for non-modifier keys alt and shift (which I have had no trouble implementing). However, I can't for the life of me figure out how to achieve the same result with a regular character key.
The example below (which I found in other comments on this site) works if the alt key is employed.
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.altKey) {
//do something, alt was down when clicked
}
});
});
However, the intuitive modification does not work.
For example, the otherwise identical code (now using event.keyCode===114) does not work (?!) when the 'r' key is pressed (nor does event.charCode===114 do the trick):
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.keyCode===114) {
//do something, alt was down when clicked
}
});
});
What went wrong?
I am able to get functionality out of a keyPress if I listen to it alone:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if(event.keyCode===114){
console.log("the 'r' key is pressed");
}
}
however nothing seems to work when I try to pair a character keypress with a mouse click or even a character keypress with a modifier keypress:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if((event.keyCode===114) && (event.altKey)){
console.log("the 'alt' and 'r' keys are pressed");
}
}
Note: I have tried keydown instead of keypress in all of these examples with no success.
Suggestions please on what I am missing or overlooking - what is problematic about pairing a character key down/press with a modifier key or a mouse click !?
Thank you!!
As I commented above, the click event does not have a property called keyCode so doing event.keyCode will not work. The only reason that control and alt work is because they are properties of the click event, event.ctrlKey and event.altKey. You can be a little more creative and use something like this maybe though I don't really know what you need:
var currKey = null;
$("#targetDiv").click(function (event) {
if (currKey != null) {
$("#targetDiv").text(currKey);
}
});
$(window).keydown(function (event) {
currKey = event.which;
});
$(window).keyup(function (event) {
currKey = null;
});
This stores the key code when keydown is fired, when keyup is fired it clears the var. The stuff in the click event is only allowed to run if the var shows something other than null.

Track first keypress event

For reasons I have to rely on keypress instead of keydown/keyup. keypress repeatedly fires events if the key is pressed. How to track only the first press on a key?
For keydown/keyup this would not be a problem, since there is a dedicated keyup event. But this is not the case for keypress.
Check the 'repeat' property of the event (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent)
If it's false then it's the first event, true otherwise.
Example using jquery:
$("#someid").on("keypress", function(e){
if(!e.originalEvent.repeat){console.log("first keypress")};
})
It's true that the "repeat" attribute doesn't work in Safari. It's only available in Gecko-based browsers. In lieu of that, try this (if you absolutely MUST use "keypress" instead of the alternatives):
var lastCode = -1;
$("#someid").on("keypress", function(e) {
var code = e.keyCode || e.which;
if (lastCode !== code) {
// do something
}
lastCode = code;
});

JavaScript: Capturing Onkeyup event only works one time

I am trying to write a web page that can catch onkeyup events.
It uses document.write("..."); to print the keycode each time.
However it only works once, the second time I use it, the window does not update.
Here is the code:
document.onkeyup = function checkKeys(event) {
var keyCode = event.which || event.keyCode;
document.write(keyCode);
};
Why does this only catch the event once?
Don't use document.write(). It's wiping the page clean, along with the onkeyup handler. Create an element on the page and update the element's contents.
document.onkeyup = function checkKeys(event) {
var keyCode = event.which || event.keyCode;
document.getElementById( 'results' ).innerText = keyCode;
};
HTML:
<div id="results"></div>
document.write(keyCode); is overwriting the page each time with the new keycode, you need to append to the document, preferably a div on the page:
<div id="keyupDiv"></div>
document.getElementById("keyupDiv").innerHTML += keyCode;

Categories