Bind arrow keys to navigation with jQuery - javascript

For the purposes of this test I have some basic html:
Previous
Next
I have a fairly straightforward jquery function:
var prev = $('.prev');
var next = $('.next');
$('body').on('keydown',function(e){
if(e.which == 37){
prev.trigger('click');
}else if(e.which == 39){
next.trigger('click');
}
console.log(e.which);
e.preventDefault();
});
The console is logging each key pressed, however this is not binding the click event to each of the href's and I am not sure why.
In addition I think using e.preventDefault(); is stopping other key actions on the page. In the other keyCode functions in my app I am not using return false or preventDefault();
Is it possible to wrap the anchors in a div and bind the keydown only to that container for example:
<div class="nav">
Previous
Next
</div>
$('.nav').on('keydown', function(){} // etc
I have a jsfiddle here: https://jsfiddle.net/lharby/sva0a4d1/

You can try this:
$('body').on('keydown',function(e){
if(e.which == 37){
$('a.prev')[0].click()
}else if(e.which == 39){
$('a.next')[0].click()
}
});

Related

How to submit the form when pressing Ctrl + S (instead of "save the webpage") in JavaScript? [duplicate]

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

Pagination jQuery next and previous control with keyboard - .trigger('click') doesn't work

I am working on pagination.
To help a user to change pages with keyboard short-keys, instead of clicking a mouse, I came up with a jQuery solution that catches user keyboard events with CTRL + → and CTRL+ ←
$(document).keydown(function(event) {
if (event.ctrlKey) { // if ctrl is being held
var keycode = event.keyCode ? event.keyCode : event.which;
if(keycode === 39) { // for rightwards arrow (for leftwards arrow keycode === 37)
window.open($('#pagination li.next a').attr('href'), '_parent'); // open the next link
}
}
});
My question is why it doesn't work with regular .trigger('click'), like this:
$('#pagination li.next a').trigger('click');
jsFiddle Live Example
$('#next').click(function() {
window.open('http://www.stackoverflow.com', '_blank');
});
$('#prev').click(function() {
window.open('http://www.google.com', '_blank');
});
$(function() {
$('#next').trigger('click')
})
I didn't find the exact answer for my question, I would like to post a slightly different and final, well working solution, based on information gathered and peoples' post. Thank you those that replied!
When you construct pagination, I believe, a user would be happy to just click ← Ctrl / Ctrl → to switch in between pages.
The following code has only one improvement - the error occurred on the first an the last page - when there are no next or previous buttons on the page, because you either on the last pagination or the first one, the initial code returned undefined (obviously), so I fixed it and would like to share the final result with those who could be possibly interested:
$(document).keydown(function (event) {
var keycode = event.keyCode ? event.keyCode : event.which;
if (event.ctrlKey) {
if (keycode === 39) {
var nextExists = $('#pagination li.next a').attr('href');
if (nextExists) window.location.href = $('#pagination li.next a').attr("href");
}
if (keycode === 37) {
var previousExists = $('#pagination li.previous a').attr('href');
if (previousExists) window.location.href = $('#pagination li.previous a').attr("href");
}
}
});

How do I capture a CTRL-S without jQuery or any other library?

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

Javascript -> Hotkeys -> Disable for input fields

okay so I have the hotkey working just can't make it stop
$(document).keypress(function(e){
if(e.which == 13){
//Enter key is press do what you want
}
else if(e.which == 67 || e.which == 99){
//C key is press do what you want
window.location.href = "/html/credits.php";
}
else if(e.which == 32){
alert("Space pressed");
}
});
$("input.registerform").keypress(function(e){
e.stopPropagation(); });
Here is what I have to make it stop, the class of my input form is "registerform bgcolor2" but it wont work with either "input.registerform" neither with "input.registerform bgcolor2" I tried adding an ID to it with registerform as ID didn't work either :/
Is it being caused my AJAX? or am I missing something here?
(Sorry I reposted this just made a new account and cant find my old question back >.<)
I understand, that since you attach your event listener to the document object, all input accepting elements, such as textfields, selects, etc. will handle hotkeys, hence lose their normal behavior.
Take a look at line 44 in the jquery.hotkeys plugin. It excludes all input-accepting elements on initialization.
P.S. Maybe this plugin is useful as a whole for your task.
The key is to check, whether an event comes from a text-accepting input.
# only bind event to text-accepting elements, if they have been
# explicitly selected
# if your event variable happens to be called e, please adjust accordingly
if ( this !== event.target &&
( /textarea|select/i.test( event.target.nodeName ) ||
event.target.type === "text") ) {
return;
}
As your code stands now, you would need to insert this snippet at the beginning of the anonymous function, you bind to the keypress event.
Seems to be working just fine :)
example:
First example: http://jsfiddle.net/HenryGarle/SG5Um/
Second example: http://jsfiddle.net/HenryGarle/SG5Um/1/
New code:
$(document).keypress(function(e){
if(e.which == 13){
alert("Enter");
}
else if(e.which == 67 || e.which == 99){
alert("c");
//window.location = 'whateveryouwant';
}
else if(e.which == 32){
alert("Space pressed");
}
});
$("input.registerform.bgcolor2").live('keypress', function(e){
alert("Stopped");
e.stopPropagation();
});
Stops:
<input class="registerform bgcolor2" type="text">
<br>
Does not stop:
<input class="registerform" type="text">
Using this anything with ONLY registerform will act as normal but if it ALSO has bgcolor2 it will stop the event.

Javascript: Escape key = browser back button

In a browser how can I make the keyboard's escape key go back in Javascript.
For example: if you visit this page and click the "Fullscreen" link I'd like to press the escape key and go back to the previous page.
What's the Javascript to make this magic happen?
You can add a Key-Listener:
window.addEventListener("keyup", function(e){ if(e.keyCode == 27) history.back(); }, false);
This will call history.back() if the Escape key (keycode 27) is pressed.
$(document).bind("keyup", null, function(event) {
if (event.keyCode == 27) { //handle escape key
//method to go back }
});
You can bind an onkeyup event handler to window and check if the keycode is 27 (keycode for Escape), then use the window.history.back() function.
window.onkeyup = function(e) {
if (e.keyCode == 27) window.history.back();
}
MDC docs on window.history, https://developer.mozilla.org/en/DOM/window.history
Just listen for key code 27 and call history.go(-1);
You need to listen for the 'ESC' keypress, and fire off the back action when it is pressed, like so:
document.onkeydown = function(e){
if (window.event.keyCode == 27) {
history.go(-1);
}
};

Categories

Resources