I'm trying to bind a key to my entire page except to one class of elements.
$('*').not('.textarea-note').keypress(function (event) {
// if key pressed is space
if (event.which == 32) {
alert('space pressed');
event.preventDefault();
}
});
The problem is that I need to do the preventDefault() and when I'm in a textarea then I can't make a space caracter.
Am I doing something wrong or it's not possible to bind to everything except some class or something.
Thanks in advance !
Edit :
After the comment from Roland, I came up with this instead which is working perfectly.
$(document).keypress(function (event) {
// if key pressed is space
if (event.which == 32 && event.target.nodeName != "TEXTAREA") {
if (videoPlaying) {
pauseVideo();
} else {
playVideo();
}
event.preventDefault();
}
});
I think you are looking for this...
$(document).keypress(function(event) {
// if key pressed is space
if (event.which == 32) {
if (event.target.id !== "a1") {// for class $(event.target).attr('class')
alert('space pressed');
event.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="a1"></textarea>
<textarea id="a2"></textarea>
<textarea id="a3"></textarea>
Related
I'm trying to do a function if enter is pressed while on specific input.
What I'm I doing wrong?
$(document).keyup(function (e) {
if ($(".input1").is(":focus") && (e.keyCode == 13)) {
// Do something
}
});
Is there a better way of doing this which would say, if enter pressed on .input1 do function?
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
event.key === "Enter"
More recent and much cleaner: use event.key. No more arbitrary number codes!
NOTE: The old properties (.keyCode and .which) are Deprecated.
const node = document.getElementsByClassName("input1")[0];
node.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// Do work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keyup", ({key}) => {
if (key === "Enter") {
// Do work
}
})
If you must use jQuery:
$(document).keyup(function(event) {
if ($(".input1").is(":focus") && event.key == "Enter") {
// Do work
}
});
Mozilla Docs
Supported Browsers
$(document).keyup(function (e) {
if ($(".input1:focus") && (e.keyCode === 13)) {
alert('ya!')
}
});
Or just bind to the input itself
$('.input1').keyup(function (e) {
if (e.keyCode === 13) {
alert('ya!')
}
});
To figure out which keyCode you need, use the website http://keycode.info
Try this to detect the Enter key pressed in a textbox.
$(function(){
$(".input1").keyup(function (e) {
if (e.which == 13) {
// Enter key pressed
}
});
});
The best way I found is using keydown ( the keyup doesn't work well for me).
Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)
$('input').keydown( function( event ) {
if ( event.which === 13 ) {
// Do something
// Disable sending the related form
event.preventDefault();
return false;
}
});
It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
The solution that work for me is the following
$("#element").addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// do something
}
});
Try this to detect the Enter key pressed in a textbox.
$(document).on("keypress", "input", function(e){
if(e.which == 13){
alert("Enter key pressed");
}
});
DEMO
A solution that worked for me is this:
<input onkeydown="if (event.key == 'Enter'){//do logic}else{}">
$(document).ready(function () {
$(".input1").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
});
This code handled every input for me in the whole site. It checks for the ENTER KEY inside an INPUT field and doesn't stop on TEXTAREA or other places.
$(document).on("keydown", "input", function(e){
if(e.which == 13){
event.preventDefault();
return false;
}
});
Here is what I did for my angular project:
HTML:
<input
class="form-control"
[(ngModel)]="searchFirstName"
(keyup)="keyUpEnter($event)"
/>
TypeScript:
keyUpEnter(event: KeyboardEvent) {
if (event.key == 'Enter') {
console.log(event);
}
}
I have forms on different pages of my applications. Upon pressing 'Enter' or 'Esc', the form on the current page must be 'Submitted' or 'Cancelled'. The keydown() function should be triggered anywhere on the page and not tied to a specific DOM element.
.js
$(document).keydown(function(e) {
if(e.which == 13) {
// enter pressed
$('#submitCreateAccountForm').click();
$('#submitForm').click();
$('#submitNewSubmissionForm').click();
}
if(e.which == 27) {
// esc pressed
$('#submitCreateAccountFormCancel').click();
$('#submitFormCancel').click();
$('#submitNewSubmissionFormCancel').click();
}
});
What should 'document' be replaced by? Thanks
try this
$(function(){
$('html').bind('keypress', function (e) {
if (e.keyCode == 13) {
//do somethings
}
else if (e.keyCode == 27) {
return false;
}
});
});
You can try this code:
$("body").keyup(function(event){ // bind keyup event to body
if(event.keyCode == 13){ // 13 - code of enter key (find for ESC)
$("#enter").click(); // bind enter press for clicking botton with id="enter" and corresponding actions
}
});
In chrome(windows), I can capture keypresses on characters, but not on the arrowkeys. See sample-code below:
$('body').on('keypress', function(e) {
console.log('Only works on charcters, in chrome')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How can I capture arrow-key-presses?
Try changing keypress to keyup:
$('body').on('keyup', function(e) {
console.log('Works on everything :)')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I think keydown is working fine
$('body').on('keydown', function(e) {
console.log('Only works on charcters, in chrome')
});
Fiddle
I really like this module for key press triggers:
https://github.com/madrobby/keymaster
It really reduces the amount of boilerplate code you need to write when working with key presses.
// define short of 'down'
key('down', function(){ alert('you pressed down') });
How can I capture arrow-key-presses?
Use e.keyCode to detect which key is pressed.
Like this :
$('body').on('keyup', function(e) {
if (e.keyCode == '38') {
alert("up arrow");
}
else if (e.keyCode == '40') {
alert("down arrow");
}
else if (e.keyCode == '37') {
alert("left arrow");
}
else if (e.keyCode == '39') {
alert("right arrow");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Simply I have a js script that change the page with left and right arrows, but how to stop that if a specific textarea is selected ?
This is my js to change the page
$(document).keydown(function(event) {
if(event.keyCode === 37) {
window.location = "http://site.com/pics/5";
}
else if(event.keyCode === 39) {
window.location = "http://site.com/pics/7";
}
});
$('textarea').on('keypress', function(evt) {
if ((evt.keyCode === 37) || (evt.keyCode === 39)) {
console.log('stop propagation');
evt.stopPropagation();
}
});
See example fiddle: http://jsfiddle.net/GUDqV/1
Update: after OP clarification this works even on jQuery 1.2.6 on Chrome: http://jsfiddle.net/GUDqV/2/
$('textarea').bind('keyup', function(evt) {
if ((evt.keyCode === 37) || (evt.keyCode === 39)) {
console.log('stop propagation');
evt.stopPropagation();
}
});
see screenshot of this code on Chrome and jQ1.2.6
Probably the simplest approach is to factor event.target into your code, checking to see if it is the textarea:
$(document).keydown(function(event) {
if (event.target.id == "myTextArea") {
return true;
}
else if(event.keyCode === 37) {
window.location = "http://site.com/pics/5";
}
else if(event.keyCode === 39) {
window.location = "http://site.com/pics/7";
}
});
Any key events that originate from a textarea element with an id of myTextArea will then be ignored.
You can check if the textarea is in focus by doing something like:
if (document.activeElement == myTextArea) {
// Don't change the page
}
$("#mytextarea").is(":focus") This will let you know if the element is focused.
Also $(document.activeElement) will get the currently focused element.
You can check to see if your text area is focused, and disable the script that navigates when using left and right arrow keys.
A little bit of code showing what you've tried might bring in more specific responses.
Hope this helps.
I have this function where #text_comment is the ID of a textarea:
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
}
});
What is happening is the text is appending when the enter/return key is hit (keyCode 13), but it is also moving the text a line down, as the enter/return key is supposed to.
This is occurring even though I set the value of the textbox to "".
How about event.preventDefault()
Try and stop your event propagation (See http://snipplr.com/view/19684/stop-event-propagations/) when entering the if(e.keyCode == 13) case.
try this one event.stopImmediatePropagation()
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
e.stopImmediatePropagation()
///rest of your code
}
});
I've tested this out, this works. The enter does not create a new line.
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
return false;
}
});
Although I am wondering, if you don't want to ever have a new line, why are you using a textarea, why not use a input type='text' instead ?
Answer here http://jsfiddle.net/Z9KMb/