My html contains list of elements. I want to use the arrow keys to select the elements.
Here is my Code: [http://jsfiddle.net/T8S7c/]
What I want is on preesing the keys the focus needs to be in the selected element like hover effects.( For example if I press the down key for the first time Ambaji has to be in focus)
I know the code of the key event but i dont know how to get the focus on the keypress.
Can anyone help me in this
My strategy for solving this would be to specify an order of focus through an array of the links, as well as having some variable specifying which link should be in focus.
var order = new Array("l1", "l2", "l3", "l4");
var current = -1;
function updateCurrent(inc) {
current = (current + inc) % order.length;
current = Math.max(current, 0);
}
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 38:
updateCurrent(-1);
document.getElementById(order[current]).focus();
break;
case 40:
updateCurrent(1);
document.getElementById(order[current]).focus();
}
};
Updated your script. Have a look at this. Fiddle : http://jsfiddle.net/T8S7c/6/
var myLinks = document.getElementsByTagName("a");
var myLinksIndex = 0;
myLinks[myLinksIndex].focus();
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 38: // Up arrow
if(myLinksIndex > 0){myLinks[-- myLinksIndex].focus();}
break;
case 40:// Down arrow
if(myLinksIndex < myLinks.length){myLinks[++ myLinksIndex].focus();}
break;
}
};
Related
Simply put, is there any way to detect additional mouse button presses in JavaScript? It's not documented with the rest of the mouse input, so I guess it's not in standard implementation.
Is there any way, such as a library, which can enable extra mouse buttons?
Yes you could do this, check MouseEvent.button, see example below that will detect 3 and 4 buttons click.
Some pointing devices provide or simulate more buttons. To represent such buttons, the value must be doubled for each successive button (in the binary series 8, 16, 32, ... ) as mentioned in https://www.w3.org/TR/DOM-Level-3-Events/#events-mouseevents
var whichButton = function (e) {
// Handle different event models
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 3:
console.log('Browser Back button clicked.');
break;
case 4:
console.log('Browser Forward button clicked.');
break;
default:
console.log('Unexpected code: ' + btnCode);
}
}
}
<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">Click with mouse...</button>
var whichButton = function (e) {
// Handle different event models
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 3:
console.log();
break;
case 4:
console.log();
break;
default:
console.log('Unexpected code: ' + btnCode);
}
}
}
I am not advanced with Javascript. i was hoping for someone to simply explain the process to edit the following code.
this.hideNextButton();
this.hidePreviousButton();
var that = this;
Event.observe(document, 'keydown', function keydownCallback(e) {
var choiceID = null;
switch (e.keyCode) {
case 74: // 'j' was pressed
choiceID = 1;
break;
case 75: // 'k' was pressed
choiceID = 2;
break;
}
if (choiceID) {
Event.stopObserving(document, 'keydown', keydownCallback);
that.setChoiceValue(choiceID, true);
that.clickNextButton();
}
});
If a user wants to replace the click of a mouse with clicking a letter on the Keyboard, eg. Click J for the next question or to select yes, click A. I think that is what this code is doing but I'd like to pull it apart a bit to add or remove letters to complete additional tasks, such as next question etc.
Any help or pointing in the right direction is a help!
In the code you provided pressing 'j' or 'k' answers the current question by setting the choice value and goes to the next page. To add other keyboard presses you would additional cases to the switch using the appropriate keycode. For example, if you wanted 'j' to just go to the next page and 'a' to answer 'Yes', it would be something like this (remove the if(choiceID) section):
Event.observe(document, 'keydown', function keydownCallback(e) {
switch (e.keyCode) {
case 65: // 'a' was pressed
that.setChoiceValue(1, true);
break;
case 74: // 'j' was pressed
Event.stopObserving(document, 'keydown', keydownCallback);
that.clickNextButton();
}
});
You need to track pointed pointed element and call click event of pointed element when the key j is pressed.
var pointedElement;
document.onmousemove = function(e) {
pointedElement = e.srcElement;
}
document.onkeydown = function(e) {
switch (e.keyCode) {
case 74: // 'j' was pressed
pointedElement.click()
break;
}
}
Edit: My answer was just about the idea to change a click element in the whole window with another key but in your case you it is different. I can not help you by just looking this snippet but you need to change switch case block with the same functionality of buttons. What exactly those buttons are doing? You need to call the same functionality of next and previous keys are handling.
The following script does what it should, that is, it reacts on the keys "arrow left" and "arrow right". However, due to a keycode clash, it reacts on a single quote as well. It makes it impossible to enter that character into an input field. Can anything be done about that?
<script type="text/javascript">
onload = function(){
document.onkeypress=function(e){
if(window.event) e=window.event;
var keycode=(e.keyCode)?e.keyCode:e.which;
switch(keycode){
case 37: window.location.href='set.jsp?index=5';
break;
case 39: window.location.href='set.jsp?index=7';
break;
}
}
}
</script>
When the user presses the single quote key, the e.keyCode property is zero, and the e.which property is 39. Executing String.fromCharCode(39) returns a single quote.
You want the keyCode if that property is in the event object:
var keycode = "keyCode" in e ? e.keyCode : e.which;
That way you get zero for the keyCode when that property exists in the event object, and when the which property also exists.
document.onkeydown = function(event) {
event = event || window.event;
var keyCode = "keyCode" in event ? event.keyCode : event.which;
switch (keyCode) {
case 37: console.log("37 was pressed", event); break;
case 39: console.log("39 was pressed", event); break;
}
};
Edit #1: Other commenters and answers are correct. I forgot you shouldn't be detecting control keys with keypress events. Changed to onkeydown.
Full HTML example that works cross browser:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Key Codes Test</title>
</head>
<body>
<script type="text/javascript">
document.onkeydown = function(event) {
event = event || window.event;
var keyCode = "keyCode" in event ? event.keyCode : event.which;
switch (keyCode) {
case 37: console.log("37 was pressed", event); break;
case 39: console.log("39 was pressed", event); break;
}
};
</script>
<input type="text" size="30">
</body>
</html>
keypress should not capture control keys like left/right arrow. if you use keydown event, single quote keycode is 222 definitely no conflict
As it is a text input, it seems you'd also have a problem when someone is trying to use the arrow keys to move the cursor within the input. Thus, stopping event propagation/bubbling should be used, and can solve the main issue you're asking about.
// assuming you've grabbed an input in var input_ele
input_ele.onkeypress = function (e) {
e = e || window.event;
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
};
Using this will stop the keypress event from leaving the input element, thereby never reaching the document element to trigger the unwanted behavior. In other words, you don't break the expected behavior of a very standard control element.
Use keydown instread of keypress
jS:
document.onkeydown=function(event){
if(window.event) event=window.event;
var keycode=(event.keyCode)?event.keyCode:event.which;
switch(keycode){
case 37: alert("an arrow");
break;
case 39: alert("another arrow");
break;
}
}
Fiddle : http://jsfiddle.net/p9x1Lj4u/2/
I have 2 links: <a href='leftLink.php'><< Prev</a> and <a href='rightLink.php'>Next >></a>.
Can it be possible to go to leftLink when pressing left arrow from keyboard, and to rightLink.php when pressing right arrow from keyboard? Any advice would be very welcome
Thank you in advance.
You can setup a keyboard event listener (keydown or keyup) on the document.
document.addEventListener('keydown',(event)=>{});
Check the key property (modern browsers) or keyCode (deprecated, older browsers) on the event object for the appropriate value corresponding to the left and right arrows.
switch(event.key){
case 'ArrowLeft':
break;
case 'ArrowRight':
break;
}
Then use the click() method of the respective link to trigger the navigation.
document.getElementById("prevLink").click();
let prevLink = document.getElementById("prevLink");
let nextLink = document.getElementById("nextLink");
document.addEventListener("keydown", ({key}) => {
switch (key) {
case 'ArrowLeft':
console.log('Left arrow');
prevLink.click();
break;
case 'ArrowRight':
console.log('Right arrow');
nextLink.click();
break;
}
});
<a id="prevLink" href='#prevUrl'><< Prev</a>
<a id="nextLink" href='#nextUrl'>Next >></a>
Use this to detect keypress..
function checkKey(e) {
var event = window.event ? window.event : e;
if (true) {
alert(event.keyCode)
}
}
from here determine the key pressed and use document.location to redirect the browser.
keycodes are:
left = 37
up = 38
right = 39
down = 40
You can try this:
$("body").keydown(function(e) {
if(e.keyCode == 37) { // left
//your code
window.location.href = "leftLink.php";
}
else if(e.keyCode == 39) { // right
//your code
window.location.href = "rightLink.php";
}
});
Reference
I have added an event listener in JS to listen for keyup/keydown events, I am attempting to move a sprite across the HTML canvas. I have that mostly working, but the page is being scrolled when the user presses the arrow keys.
I am returning false, and that does not seem to work. In addition, my understanding is that returning false in this manner would disable arrow button scrolling for the entire page. I would like to only disable this while the user is interacting with the canvas itself.
Here is my event listener:
addEventListener('keydown', function(e){
move = false;
x = false;
y = false;
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
switch(keycode){
case 37:
move = true;
x = 'negative';
break;
case 38:
move = true;
y = 'negative'
break;
case 39:
move = true;
x = 'positive'
break;
case 40:
move = true;
y = 'positive'
break;
}
if(move){
animation.move(x,y);
}
return false;
})
Edit:
The below answer has a good idea of how to make sure that the canvas is focused, but I am still puzzled why returning false in my EventListener function which returns false is not disabling scrolling.
As long as you are giving your canvas focus somehow (ie canvas.tabIndex = 1;) then you can just add e.preventDefault() right before your return false and it will work.
Example:
http://jsfiddle.net/faAkN/
I had a similar problem, and came up with a fix.
Here's what I came up with:
function $(){
return document.querySelector.apply(document,arguments);
}
var canvas = $('canvas'),
keysDown = []; // You can also define this as an object, {}
canvas.tabIndex = 0;
canvas.onclick = function(e){
document.body.scrollTop = canvas.offsetTop; // scrolls to canvas element
canvas.focus(); // re-focuses canvas in case the scroll unfocused it
}
canvas.onkeydown = canvas.onkeyup = function(e){
keysDown[e.keyCode] = e.type == 'keydown';
e.preventDefault();
return false;
}
function isDown(key){
return keysDown[key];
}
function resetMap(){
keysDown = [];
return false;
}
To check if a key is down, use isDown(keycode) either in an interval loop or in a keydown function.
For a regular key listener:
canvas.onkeydown = canvas.onkeyup = function(e){
// [...]
if(isDown(17) && isDown(32)){ // Ctrl + Space
alert('Ctrl and Space were pressed');
resetMap();
}
e.preventDefault();
return false;
}
For a rapid key listener similar to ActionScript 2.0's Key.isDown
function KeyLoop(){
if(isDown(17) && isDown(32)){ // Ctrl + Space
console.log('Lots of text');
resetMap();
}
setTimeout(keyLoop,1000/24); // # 24 fps
}
keyLoop();
I put a different action here for two reasons: 1) Mixing alert() with a repeating interval is never a good idea, and 2) to demonstrate the lack of delay, which is what makes this similar to the AS2 Key.isDown() function. To see the logged text, bring up firebug or a regular JavaScript console. In Chrome, that's CtrlShiftJ. In Firefox, CtrlShiftK.
This should fix your scrolling problem by focusing on the element when you click the canvas. An added benefit is that you can check for multiple keys at once since you're using keysDown[] as an abstraction from the original event, making an 8-directional game easy to make.
Have you tried something like this?
<script type="text/javascript">
canvas_active = false;
</script>
<canvas onfocus="javascript: canvas_active = true;" onblur="javascript: canvas_active = false;" />
Then in your current method check to see if the canvas_active is true and if so, return false, else return true. This would only work if the canvas is focused the whole time they are moving it, of course.