Keyboard shortcut for hyperlink (jQuery) - javascript

I have six links on my webpage (and nothing else) and I would like to number each, 1 to 6. It would be nice to have the client hit corresponding number key without the ctrl and alt, etc.
Is this possible and what would be the best approach with jquery or other html scripts?

Here is one version, for jQuery:
$(document).ready(function() {
$("body").keypress(function(event) {
var link = "#link";
if(event.keyCode == 49) link += 1;
if(event.keyCode == 50) link += 2;
if(event.keyCode == 51) link += 3;
if(event.keyCode == 52) link += 4;
if(event.keyCode == 53) link += 5;
if(event.keyCode == 54) link += 6;
if(link != "#link") $(link).trigger("click");
});
});

Without control + key: keypress event listener in query, and listen for a particular key code per button.
With control + key: You could use an access key (http://www.cs.tut.fi/~jkorpela/forms/accesskey.html)

If you want to do this without the alt or ctrl key you'll need JavaScript. You could attach an event lister to the html or body tag and listen for the keypress event. Don't use complex 'if' statements, that is not necessary. It can be elegant like this (using jQuery):
link1
link2
etc
$('body').keypress(function(e) {
$('[code=' + String.fromCharCode(e.keyCode-48) + ']').click();
});
With the ctrl/alt key you could use the accesskey html attribute: http://reference.sitepoint.com/html/a/accesskey

$('body').bind('keypress', function(e) {
if(e.keyCode==49){ // number 1 on the keyboard been pressed
$('firstHref').click();
} else if(e.keyCode==50) { // number 2
$('secondHref').click();
} else if(e.keyCode==51) { // number 3
$('thirdHref').click();
}else if(e.keyCode==52) { // number 4
$('fourthHref').click();
}else if(e.keyCode==53) { // number 5
$('fiveHref').click();
}else if(e.keyCode==54) { // number 6
$('sixHref').click();
}
});

You can try something like this: Link (click the run button then click inside of the 'Result' box before you hit the numb keys.
$('body').bind('keypress', function(e) {
if(e.keyCode==49){ // 1
alert('1 key pressed');
window.location = "http://www.stackoverflow.com/"
}
if(e.keyCode==50){ // 2
alert('2 key pressed');
window.location = "http://jsfiddle.net/"
}
if(e.keyCode==51){ // 3
alert('3 key pressed');
window.location = "http://www.google.com/"
}
if(e.keyCode==52){ // 4
alert('4 key pressed');
window.location = "http://www.stackoverflow.com/"
}
if(e.keyCode==53){ // 5
alert('5 key pressed');
window.location = "http://jsfiddle.net/"
}
if(e.keyCode==54){ // 6
alert('6 key pressed');
window.location = "http://www.google.com/"
}
});​

Related

To open a new web page after pressing the enter key 3 times

I need the script for functioning the window.location only after pressing the ENTER key 3 or n times.
This is my current code and i am trying to modify it. Need help, still.
function KeyPress(f) {
var event = window.event? event : f
if (event.keyCode == 13)
window.location = './index.html';
}
document.onkeypress = KeyPress;
Following your instructions, after three press to the key ENTER, it should run the code that will call window.location. In this example, I'm using console.log to prove it is doing what you asking.
Note: When you run it, you need to click with the mouse where it says "Press Enter 3 times.". In this way, the browser will focus on that section. Then, you can press the ENTER key three times.
document.addEventListener("keyup", (e) => enterKeyPressed(e))
let counter = 1;
function enterKeyPressed(event) {
console.log("Key", event.keyCode, " Pressed:", counter);
if (event.keyCode == 13 && counter == 3) {
console.log("Enter key is pressed");
// window.location = "<url you want to go>";
return true;
}
counter++;
return false;
}
Press Enter 3 times.
Check the log.

How to detect keypresses in jQuery regardless of layout?

So basically i am trying to connect clicking links to keys in Tampermonkey. First I tried e.which, but it didn't work with different layouts. Then I tried e.code, but for some reason it only detects pressing the B key (see code below). What did I do wrong?
$(document).on("keypress", function (e) {
if(e.сode == "KeyN") {
document.getElementById("nextimage").click();
} else if(e.code == "KeyB") {
document.getElementById("previmage").click();
}
});
You can try using the KEY itself instead of the code. The toUpperCase() function will detect lowercase or uppercase :
$(document).on("keypress", function (e) {
if(e.key.toUpperCase() == "N") {
alert("yay!")
} else if(e.key.toUpperCase() == "B") {
alert("nay");
}
});
Here's a reference with the different key codes: https://keycode.info/
Try this to read keys.
Make sure you have the JQuery reference.
$(document).keypress(function(event) {
alert('You pressed - ' + event.key.toUpperCase());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
and here is javascript in case:
const myText = document.getElementById('myText');
document.addEventListener('keypress', logKey);
function logKey(e) {
myText.textContent += e.key.toUpperCase();
if(e.key.toUpperCase() == 'N')
alert("You Pressed N key");
}
and
<p id="myText"></p>

Multiple keyup events in one JS FILE

I have a JS file for my HTML web page. I want to have 4 things to check. If they hit a number, 1-4 on the keypad, it takes them to a specified url. The script works, but only if I have one.
When I put all 4 events in the js file, only the last one/most recent one works. Is there some kind of syntax that I'm doing wrong that's stopping all of 4 them from working?
To further explain, using this code, only this part of the script runs:
//If they hit keypad number 4
document.body.onkeyup = function(e){
if(e.keyCode == 52){
window.location.href = "foo";
JS:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
}
//If they hit keypad number 2
document.body.onkeyup = function(e){
if(e.keyCode == 50){
window.location.href = "foo";
}
}
//If they hit keypad number 3
document.body.onkeyup = function(e){
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
}
//If they hit keypad number 4
document.body.onkeyup = function(e){
if(e.keyCode == 52){
window.location.href = "foo";
}
}
If you put all your condition into the same function it will work great. Otherwise you will overwrite your function every times. That is why you got the issue where the only event working was the last one. Last thing, try to use if and then else if. Otherwise you will verify every conditions every single times for no reason.
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
else if(e.keyCode == 50){
window.location.href = "foo";
}
else if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
else if(e.keyCode == 52){
window.location.href = "foo";
}
}
This behavior can be explained in this way: What you were trying to do is to assign a function to the onkeyup event. This happens on a same way as when working with variables. Let's say
var key = 1;
is a "reduced" code for
document.body.onkeyup = function(e){
// action for keypad 1
}
then, when assigning another event handling function to your onkeyup, you are doing
key = 2;
Ask yourself a question: does the variable key hold 1? No. That is being overwritten by the above statement. key holds 2 now. The 1 is "lost". That is the reason why the last event handler (for keypad 4) is being executed only. The last assignment has overwritten the previous assignment.
To work around this, you have two options:
group the event actions in one function
use EventTarget.addEventListener
With option 1, you can group your actions in one function like in the interactive example here below:
// input acts as your document.body
const inp = document.getElementById('foo');
inp.onkeyup = function(e) {
if(e.keyCode == 49) {
console.log('pressed keyCode 49'); // press 1
}
else if(e.keyCode == 50) {
console.log('pressed keyCode 50'); // press 2
}
else if(e.keyCode == 51) {
console.log('pressed keyCode 51'); // press 3
}
else if(e.keyCode == 52) {
console.log('pressed keyCode 52'); // press 4
}
};
<input id="foo" type="text" placeholder="type something">
Yet sometimes that is not flexible. Maybe you want to have two different actions to the keyup event. Of course you can group that in one function but what if another js file overwrites the function? Or another snippet further in the js file? That is not productive.
To prevent this, you can use option 2: .addEventListener which is a more robust approach. Here below is an interactive example:
// input acts as your document.body
const inp = document.getElementById('foo');
inp.addEventListener('keyup', function(e) {
if(e.keyCode == 49) {
console.log('first function: keyCode 49'); // press 1
}
});
inp.addEventListener('keyup', function(e) {
if(e.keyCode == 50) {
console.log('second function: keyCode 50'); // press 2
}
});
<input id="foo" type="text" placeholder="type something">
Also, I want to add another suggestion: you were using .keyCode which is deprecated. You can still use but it is not encouraged. It is possible that the browser developers decide to drop this in the future. That leads to a not functioning code.
The problem is that each browser/OS has their own keyCodes which makes it less reliable.
For a clean approach, please consider to use KeyboardEvent.code
Hi and welcome to StackOverflow ;)
You are registering a new onkeyup event listener every time. Try putting the if statements all into one listener like this:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
if(e.keyCode == 50){
window.location.href = "foo";
}
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
if(e.keyCode == 52){
window.location.href = "foo";
}
}
I hope this helps.
Most people's answer will work however to simply avoid code duplication and a tirade of 'IF' statements, I would just use a switch statement as so :
document.body.onkeyup = function(e){
switch(e.keyCode) {
case 49:
window.location.href = "http://localhost:1337/trail";
break;
case 50:
window.location.href = "foo";
break;
case 51:
window.location.href = "http://localhost:1337/topten";
break;
case 52:
window.location.href = "foo";
break;
}
}
You are overriding the event handler, you need to have one function there. try this option:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
} else if(e.keyCode == 50){
window.location.href = "foo";
} else if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
} else if(e.keyCode == 52){
window.location.href = "foo";
}
}
Or you can use a switch instead.
Yes, there is an alternate syntax that allows for multiple event handlers to be added to the same object with out overriding one another.
addEventListener('keyup', functionHere );
/*
// This will work without overriding other functions...
//If they hit keypad number 1
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
});
//If they hit keypad number 2
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 50){
window.location.href = "foo";
}
});
//If they hit keypad number 3
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
});
//If they hit keypad number 4
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 52){
window.location.href = "foo";
}
});
*/
// It may be best to combine them all even when using this method...
document.body.addEventListener("keyup", function(e) {
//If they hit keypad number 1
if (e.keyCode == 49) {
window.location.href = "http://localhost:1337/trail";
}
//If they hit keypad number 2
if (e.keyCode == 50) {
window.location.href = "foo";
}
//If they hit keypad number 3
if (e.keyCode == 51) {
window.location.href = "http://localhost:1337/topten";
}
//If they hit keypad number 4
if (e.keyCode == 52) {
window.location.href = "foo";
}
});
Maybe add all your ifs inside one event listener:
document.body.addEventLister("keydown", function(e) {
if (e.key == "Digit1") {
window.location.href = "http://localhost:1337/trail";
}
if (e.key == "Digit2") {
window.location.href = "foo";
}
if (e.key == "Digit3") {
window.location.href = "http://localhost:1337/topten";
}
if (e.keyCode == "Digit4") {
window.location.href = "foo";
}
}

JavaScript how to make backspace work in my keyCode text prompt?

I'm creating a way to type anywhere by intercepting the keydown event instead of using a text box for a project. I'm having trouble finding out how to implement the backspace. This is a shortened version of my code:
$(document).keydown(function(event){
typed = String.fromCharCode(event.keyCode);
display += typed;
document.getElementById("text").innerHTML = letterContainer;
});
I was trying to use the .replace function like this...
if (event.keyCode == 8) {
display.replace(typed,'');
}
...and put it at the beginning, but that doesn't work. Any ideas?
You're getting there. How are you emptying the text in the input tag?
if (event.keyCode == 8) {
display.replace(typed,'');
// ^ This does not change the value of the <input>
}
I'd suggest something like:
function isDeleteKeyCode(event) {
return event && event.keyCode === 8;
}
function resetValue(element) {
element.value = '';
}
$('#input-id').keydown(function(event) {
if (isDeleteKeyCode(event)) {
resetValue(event.target);
}
// ^ This can be simplified as: isDeleteKeyCode(event) && resetValue(event.target)
});
That would add a keydown listener to an input tag with id="input-id".
Demo: https://jsfiddle.net/pp16tru7/
var display = '';
$(document).keydown(function(event) {
var typed = String.fromCharCode(event.keyCode);
// if backspace, get text without the last character, else add character to display
if (event.keyCode === 8) {
display = display.substr(0, display.length - 1);
} else {
display += typed;
}
document.getElementById("text").innerHTML = display;
});

Different actions on multiple Keydown event

Okay, so my question (im hoping) is fairly simple. I want to know what to do so that I can create different events for the same keycode. For instance Id like to fade out a div and fade a new one in on the first keypress, then fade that one out and fade a new one in on keypress.
Thanks!
$(document).keydown(function() {
if (event.keyCode == '40') {
$('.div-1').fadeOut("slow")
$('.div-2').fadeIn("slow")
// I'd like this event to occur on the Second keydown
$('.div-2').fadeOut("slow")
$('.div-3').fadeIn("slow")
}
});
try
var hits = 0;
$(document).keydown(function() {
if (event.keyCode == '40') {
hits++;
if (hits % 2 == 0) {
// I'd like this event to occur on the Second keydown
$('.div-2').fadeOut("slow");
$('.div-3').fadeIn("slow");
} else {
$('.div-1').fadeOut("slow");
$('.div-2').fadeIn("slow");
}
});
The only solution I can see is create local variable. In your case (slodeshow) you need to count each keydown and parse div class.
var hits = 0;
$(document).keydown(function() {
if (event.keyCode == '40') {
$('.div-' + hits).fadeOut("slow")
$('.div-' + (hits + 1)).fadeIn("slow")
hits++;
}
});

Categories

Resources