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.
Related
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("لقد قمت بالصغط على مراقبة مع حرف السين");
});
I am having some problems with executing a function depending on whether the 'blur' or 'keydown' event is triggered.
I am having the following situation:
$(document).ready(function() {
function blurChange(e) {
clearTimeout(blurChange.timeout);
blurChange.timeout = setTimeout(function() {
var keycode = (e.keyCode ? e.keyCode : e.which);
var entered_date = $('.format').val().split('-');
if (entered_date[2].length == '4' && (entered_date[1].length == '2' || entered_date[1].length == '1') && (entered_date[0].length == '2' || entered_date[0].length == '1')) {
console.log("yes");
$('.formatted-date').off('blur change');
} else {
$('.error').html("error");
}
}, 10);
}
$('.format').on('blur keydown', blurChange);
});
HTML:
<input class="format" value="01-02-2099">
<span class="error"></span>
The situation that I am seeking for is to have an input field where a user can fill any date in the given format and when the input lost his focus the console.log is triggered. I also want that this console.log is triggered when pressing the 'enter' button (event code 13).
In short,
I want to have two situations working:
Situation 1: The input is checked with the if statement if the user is blurring (unfocus)
Situation 2: The input is checked with the if statement if the user press enter within the input field.
So in both situations(blur, onkeyenter) the input should be checked. I hope that I made myself clear. For any questions please ask.
DEMO HERE: JSFIDDLE
Not changing your code too much, you could simply do:
if((e.type == "keydown" && keycode == 13)
|| e.type == "blur")
Before your current if statement.
JsFiddle
Although it may make more sense to separate them like here:
Possible better way
I've also added this $('.error').html(""); so the error message clears when data is correct.
I have a web application where on one specific screen I have to make sure the user clicked the button using the mouse as opposed to just pressing enter or space.
I have written this code:
$('button').keydown(function (e) {
if (e.which === 10 || e.which === 13 || e.which === 32) {
return false;
}
});
However, this only works for enter. The form can still be submitted by pressing space on a button. I am just wondering what caused this inconsistency and how to get around it?
Edit:
Example fiddle: http://jsfiddle.net/billccn/3JmtY/1/. Check the second check box and pressing enter while the focus is on the button will have no effect. If I further disable the input and expand the keydown trapping to the whole form, then enter cannot be used to submit the form.
Edit 2:
I do have a backup plan which is replacing the button with a link or even a plain div and use the click event to submit the form programmatically. However, extra work is required to make it look like a button so I'd rather use a button is possible.
Just found out: handling space (32) on keyup will prevent the click event.
Updated fiddle: http://jsfiddle.net/3JmtY/2/
Missed the Point of your Question. After some googleing if found the following trick:
Bind the keypress event to your from and listen to it's keycode. If the keycode is 13
(enter), prevent all default actions (event.preventDefaul()) and prevent further event bubbeling ( return false; ).
Her is a fiddler code example:
HTML:
<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">Trigger the handler</div>
JavaScript:
$('#target').keypress(function (event) {
var code = event.keyCode || event.which;
if (code == 13) {
event.preventDefault();
return false;
}
});
$('#target').submit(function (event, data2) {
debugger;
alert('test');
return false;
});
Fiddler: http://jsfiddle.net/ggTDs/
Note that the form is not submited when enter is clicked!
Use below code. 13 for Enter key and 32 for Spacebar.
$("#form_id").on('keydown keyup keypress', function( e ) {
if ( e.keyCode == 13 || e.which == 13 || e.which == 32 ) {
e.preventDefault();
return false;
}
});
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("لقد قمت بالصغط على مراقبة مع حرف السين");
});
I’m working with basic HTML <input type="text"/> text field with a numeric value.
I’m adding JavaScript event keyup to see when user presses arrow up key (e.which == 38) – then I increment the numeric value.
The code works well, but there’s one thing that bugs me. Both Safari/Mac and Firefox/Mac move cursor at the very beginning when I’m pressing the arrow up key. This is a default behavior for every <input type="text"/> text field as far as I know and it makes sense.
But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered).
The jump at the beginning happens on keydown but even with this knowledge I’m not able to prevent it from occuring. I tried the following:
input.addEventListener('keydown', function(e) {
e.preventDefault();
}, false);
Putting e.preventDefault() in keyup event doesn’t help either.
Is there any way to prevent cursor from moving?
To preserve cursor position, backup input.selectionStart before changing value.
The problem is that WebKit reacts to keydown and Opera prefers keypress, so there's kludge: both are handled and throttled.
var ignoreKey = false;
var handler = function(e)
{
if (ignoreKey)
{
e.preventDefault();
return;
}
if (e.keyCode == 38 || e.keyCode == 40)
{
var pos = this.selectionStart;
this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10);
this.selectionStart = pos; this.selectionEnd = pos;
ignoreKey = true; setTimeout(function(){ignoreKey=false},1);
e.preventDefault();
}
};
input.addEventListener('keydown',handler,false);
input.addEventListener('keypress',handler,false);
I found that a better solution is just to return false; to prevent the default arrow key behavior:
input.addEventListener("keydown", function(e) {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') return false;
}, false);
Actually, there is a better and simpler method to do this job.
$('input').bind('keydown', function(e){
if(e.keyCode == '38' || e.keyCode == '40'){
e.preventDefault();
}
});
Yes, it is so easy!
In my case (react) helped:
onKeyDown = {
(e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') e.preventDefault();
}
}
and onKeyUp was fully functional
I tested the code and it seems that it cancels the event but if you don't press the arrow for very short time - it fires keypress event and that event actually moves cursor. Just use preventDefault() also in keypress event handler and it should be fine.
Probably not. You should instead seek for a solution to move the cursor back to the end of the field where it was. The effect would be the same for the user since it is too quick to be perceived by a human.
I googled some and found this piece of code. I can't test it now and it is said to not to work on IE 6.
textBox.setSelectionRange(textBox.value.length, textBox.value.length);