Do something on left/right arrow press - javascript

I want to trigger a click event on another element, when a left or right arrow is pressed. Here is the code:
$(window).keypress(function (e) {
var key = e.which;
if(key == 13 || key == 39) { // the enter key code or right arrow
$('.next').click();
return false;
} else if(key == 37) { // left arrow
$('.prev').click();
return false;
}
});
With Enter key it works like a charm, however on arrow press, nothing happens, like a Magikarp that uses splash! :) What am I missing?
Relevant question: Press left and right arrow to change image?

The arrow keys don't trigger a keypress event, but they do trigger a keyup or keydown event.
Best to use keyup, because keydown can be triggered multiple times while you're holding down a key.
$(window).keyup(function (e) {
var key = e.which;
if(key == 13 || key == 39) { // the enter key code or right arrow
$('.next').click();
return false;
} else if(key == 37) { // left arrow
$('.prev').click();
return false;
}
});

Related

How to track clicks of one button and then another?

I need to track the click on capslock and then the keyboard shortcut ctrl + alt, that is, first click on capslock and then on the keyboard shortcut here is an example
if (e.code == "CapsLock") {
if (e.ctrlKey && e.keyCode == 18) {
alert();
}
}
but this code does not work
I use a function like this:
document.addEventListener("keydown", function (e) {
var caps = e.getModifierState && e.getModifierState('CapsLock'); // true if pressed, false if released
document.onkeyup = function(event) {
if(caps === true){
/** Validate keys are to be processed */
var keycode = event.which;
// works off course only if ctrl key is kept pressed during key stroke = normal behavior in most OS
// Should it work like a ctrl-Lock function you have to work with a state variable
if ((event.ctrlKey === true) && (keycode === 18)) {
alert();
}
else{
/** Let it happen, don't do anything */
return;
}
}
};
});

Keydown on up arrow not preventing default, still makes div scroll

I have a chat area, where messages go, and a chat input below. As you can see in this structure:
After load I run this function:
function activate_key_detection()
{
$(document).keydown(function(e)
{
code = (e.keyCode ? e.keyCode : e.which);
if(e.ctrlKey)
{
if(window.getSelection().toString() != "")
{
return;
}
}
$('#chat_input').focus();
if(code == 13)
{
send_to_chat();
e.preventDefault();
return false;
}
if(code == 38)
{
$('#chat_input').val(last_input);
e.preventDefault();
return false;
}
if(code == 27)
{
if($('#overlay').css('display') == 'block')
{
hide_boxes();
e.preventDefault();
return false;
}
else
{
clear_input();
}
}
});
}
As you can see it first focuses the input, and when the key is the up arrow (38) it catches it, modifies the input and tries to prevent the default behavior of they key.
The problem is, when I first click inside the chat area, and then press the up arrow, it will still scroll the chat area a line. Subsequent presses of the up arrow don't scroll the chat area further.
I tried adding e.stopPropagation() there too, to no avail.
Any help is welcome.

Use arrow keys to change focus on buttons

I am using the JQuery UI Dialog to create a pop-up. The pop-up has two buttons. The first button is automaticly selected by JQuery. I can change the selection between the buttons and the exit button with 'tab'.
I want to change the selection (only between the two buttons) also with the left and right arrow keys on the keyboard.
Where do I have to catch the arrow key down events and how can I change the focus of the buttons?
Thanks for your help!
I would do it something like that :)
$('body').on('keydown', '#terug', function(e) {
if (e.keyCode === 39) { //right arrow
$('#ok').focus();
}
});
$('body').on('keydown', '#ok', function(e) {
if (e.keyCode === 37) { //left arrow
$('#terug').focus();
}
});
Try it :) And if this won't work then go global without specifying selector in event definition:
$('body').on('keydown', function(e) {
if (e.keyCode === 39 && $('#terug').is(':focus')) { //right arrow
$('#ok').focus();
}
});
Hope this will help! :) If not give me a comment and i will try to fix this. :)
Thanks for your help! It worked. I added my solution to complete this question.
I bind the keydown event only on the ui-buttons:
$(document).on('keydown', '.ui-button', handleUIButtonKeyDown);
After that I handle the left and right arrow keys
function handleUIButtonKeyDown(event) {
if (event.keyCode == 37) {
//left arrow key pressed, select the previous button
makeButtonFocus($(this).prev(".ui-button"));
} else if (event.keyCode == 39) {
//right arrow key pressed, select the next button
makeButtonFocus($(this).next(".ui-button"));
}
}
function makeButtonFocus($button) {
$button.addClass("ui-state-focus");
$button.focus();
}
Here's a more generic answer
works on any number of buttons irregardless of DOM structure (btns need not be siblings)
$('body').on('keydown', function(e) {
if (e.keyCode === 37) { //left arrow
modalKeyboardNav("prev")
} else if (e.keyCode === 39) { //right arrow
modalKeyboardNav("next");
}
});
function modalKeyboardNav(dir) {
if (!$("body").hasClass("modal-open")) {
// no modal open
return;
}
var $curModal = $(".modal.show"),
$curFocus = $(document.activeElement),
$focusable = $curModal.find(".btn"),
curFocusIdx = $focusable.index($curFocus);
if (curFocusIdx < 0) {
// nothing currently focused
// "next" will focus first $focusable, "prev" will focus last $focusable
curFocusIdx = dir == "next" ? -1 : 0;
}
if (dir == "prev") {
// eq() accepts negative index
$focusable.eq(curFocusIdx - 1).focus();
} else {
if (curFocusIdx == $focusable.length - 1) {
// last btn is focused, wrap back to first
$focusable.eq(0).focus();
} else {
$focusable.eq(curFocusIdx + 1).focus();
}
}
}

Detecting left and right control keys in Javascript

I have a text input, where I need to bind an event on doing a CTRL-V. I have set a global variable named ctrl which is set to 1 whenever a keydown is fired with a which value of 17. Similarly it is made 0 when a keyup is fired with which value of 17
Problem is, there are two CTRL keys. So if I do something like: first pressing the left CTRL key, and while pressing it down, press the right CTRL key also (so that both CTRL keys are pressed now), and then I release only one of them, the keyup is fired and the variable ctrl is set to 0, even though the other CTRL key is still being pressed.
How do I fire the events such that the variable is set to 0 only when both CTRL keys are up (I don't need to exactly differentiate between them).
Update : this is now possible in modern browsers
The easiest way to detect left and right control keys in Javascript
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (event.location == 1) console.log('left ctrl');
if (event.location == 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: You have to click the inside white space when you run code snippet to activate keyboard keys. This is tested in Chrome and Safari.
There are two properties for this of keydown event.
You can differentiate left and right Ctrl by using
if ( e.location == 1 || e.keyLocation == 1 ) {
var keyPosition = 'left';
} else if ( e.location == 2 || e.keyLocation == 2 ) {
var keyPosition = 'right';
}
I don't think there is a way for that unless you write on lowlevel ... keyCode is the same for both (it is 17)
Just You can use e.ctrlKey as a way to determine if the control key was pressed.
However I read around and found one answer mentioning you could do that in IE but I did not try it from my side
you can use e.originalEvent.location instead of the global event.location
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (e.originalEvent.location === 1) console.log('left ctrl');
if (e.originalEvent.location === 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
below is your answer for three mouse keyup events. rest for mousewheel you should ask again:
/*
1 = Left Mousebutton
2 = Centre Mousebutton
3 = Right Mousebutton
*/
$(document).mousedown(function(e) {
if (e.which === 3) {
/* Right Mousebutton was clicked! */
alert("right key code 3");
}
else if(e.which === 2) {
alert("Centre key code 2");
}
else if(e.which === 1) {
alert("Left key code 1");
}
});
you can use this:
$('#inputboxinput').bind('keypress', function(e) {
if(e.keyCode==13){
// Enter pressed... do anything here...
}
});
the cross-browser way:
if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode: event.keyCode)) {
event.which = event.charCode || event.keyCode;
}

jQuery handling keypress combinations

I know that when keypress event occurs then we can access which key is pressed by object's event property keycode, but I need to know how do we can handle keypress combinations through jQuery like ctrl + D ..etc?
In the following code I tried to do something like :
$(document).on("keypress", function(e) {
if( /* what condition i can give here */ )
alert("you pressed cntrl + Del");
});
jQuery already handles this for you:
if ( e.ctrlKey && ( e.which === 46 ) ) {
console.log( "You pressed CTRL + Del" );
}
I know that this is an old question that has already been answered, but the answer marked as correct did not work for me. Here is a simple and easy method for catching the key combinations I wrote:
NOTE: This example is catching ctrl + space combination, but you can easily change it to any other keys.
var ctrlPressed = false; //Variable to check if the the first button is pressed at this exact moment
$(document).keydown(function(e) {
if (e.ctrlKey) { //If it's ctrl key
ctrlPressed = true; //Set variable to true
}
}).keyup(function(e) { //If user releases ctrl button
if (e.ctrlKey) {
ctrlPressed = false; //Set it to false
}
}); //This way you know if ctrl key is pressed. You can change e.ctrlKey to any other key code you want
$(document).keydown(function(e) { //For any other keypress event
if (e.which == 32) { //Checking if it's space button
if(ctrlPressed == true){ //If it's space, check if ctrl key is also pressed
myFunc(); //Do anything you want
ctrlPressed = false; //Important! Set ctrlPressed variable to false. Otherwise the code will work everytime you press the space button again
}
}
})

Categories

Resources