jQuery call event on keydown or keyup - javascript

I am trying to change the color of a div element on a keydown and keyup but i just cant seem to get it to work. Ive check every example i can find on the internet but my code will just not seem to work.
All of the examples i find seem to use a form input text field as a target for the keypress. I dont want to do that. here is my code:
$(document).keydown(function(e){
if(e.which == 'A')
{
alert('key was pressed');
$(#k1).css('background-color', "blue");
}
});
My thought is that $(document) is not the correct thing to have there because the function is never called. But because all the examples i find use a textfield input, i just cant figure out what to put there.

LIVE DEMO
$(document).keydown(function(e){
if(e.which == 65){
alert('Pressed key was: '+ e.which );
$("#k1").css( { backgroundColor:"blue" } );
}
});
If you need $('input') instead of $(document) feel free to use it,
65 is the event.which for A

Couple of things. Firstly, the event.which will return a number which correlates to a key. And secondly, your jquery target needs to be a string. So, change the =='A' to ==65 and $(#k1) to $("#k1") and it will work. Here is a demo: http://jsfiddle.net/AeBtV/
js
$(document).keydown(function(e){
if(e.which == 65)
{
alert('A key was pressed');
$("#k1").css('background-color', "blue");
}
});
Note on key code numbers:
The range is from 65-90 for A to Z. Thus A is 65, Z is 90, and R is 82.

I've trapped keyup and keydown events using .live:
$("#my_id").live('keydown',function(event) {
...
});

Your which condition isn't valid. Should be 65 as others mentioned.
http://api.jquery.com/keypress/
If you scroll down, you can type in any key and see the which value of each key.
Alternatively, you can do
console.log(e.which);

Related

.addEventListener enquiry

So this works:
$('#divID').addEventListener('click', function() {alert('hi');}, false);
However I'm trying to get this to work, but just couldn't
$('#divID').addEventListener('keypress', function(e) {
e = event || window.event;
if (e.keyCode == 40) {
//do something when the down arrow key is pressed.
}
}, false);
Please help, much appreciated.
I'm trying to control what happens when the down arrow key is pressed but it's only for that specific divID, not for the whole document.
KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable.
Also the behaviour varies from browser to browser.
You've tagged your question jquery, so I'll assume you are actually using it.
There are several issues there:
keypress is only triggered for printable characters. For arrow keys, you want keydown (usually) or keyup (rarely).
jQuery instances don't have an addEventListener method. You want on. (Or you could use the event-specific alias for the event you want to use.)
There is no third argument to the jQuery on method.
jQuery handles the issue of the event argument being passed by some handler mechanisms and not by others for you. It always gives you the argument.
Some browsers use keyCode, others use which. jQuery standardizes it for you as which.
So:
$('#divID').on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
}
});
More: on, the event object
For the div to receive the keypress, on at least some browsers, it will need to either be or have interactive content (for instance, it would need to have an input in it, or be contenteditable, or similar).
Live Example with a contenteditable div
$('#divID').on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
$("<p>").text("down arrow").appendTo(document.body);
return false;
}
});
<div id="divID" contenteditable>Click here to ensure the div has focus, then press the down arrow</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Alternately, capture the keydown event on document.body (or document):
Live Example with document.body:
$(document.body).on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
$("<p>").text("down arrow").appendTo(document.body);
return false;
}
});
<div id="divID">Click here to ensure the document has focus, then press the down arrow</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

HTML input tag, cannot type

I have been struggling with this for a couple of days. I am pretty sure it's something simple, but I just can't see it.
On this page there is a form that users can use to send a message. Click on the grey Contact icon to see it.
The form used to work fine, but now I cannot type into any fields. Selecting an autocomplete value works though.
I have tried disabling some Javascript, adding a z-index value to the fields, but to no avail.
Can someone please take a look and tell me what might be the problem?
Thanks in advance.
You are too eager to restrict the user..
This code is the problem:
$(document).keydown(function(e){
if (e.keyCode == 39) {
//(...)
toggleArrows();
}
return false;
});
If the button IS NOT keyCode 39, you deny the button functionality.
Just remove the return false and your problem will be gone.
Edit: I just noticed you have 2 keydown events, one checking for keycode 37 and one for 39. Don't do that! You should do it this way:
$(document).keydown(function(e){
if (e.keyCode == 39) {
//(...)
}
else if (e.keyCode == 37) {
//(...)
}
});
And, again, get rid of the return false;.
JSFiddle to show the result: http://jsfiddle.net/xr2stb0k/
First checkbox is restricted with return false (except for the letter "a"), second one isn't.

jQuery keypress to work normally except hitting enter

I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?
I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode
This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.
The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo
This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo

ENTER event for jQuery

I am new to javascript; thus, it question may seem to be naive. I have a simple jQuery function as
$(document).ready(function(){
$('#txtValue').keyup(function(){
sendValue($(this).val());
});
});
This sends immediately when a letter is typed in
I explored jQuery events, but I was unable to find an event for ENTER. I want to run the function when I typed all letters and pressed ENTER.
Check the keyCode property of the event object. 13 represents the Enter key:
$('#txtValue').keyup(function(e){
if(e.keyCode === 13) {
sendValue($(this).val());
}
});
The keyup event will fire every time a key is released. There is no way to selectively fire the event, but you can choose when to handle it!
Edit
It's actually better to use event.which, to deal with all browsers, as jQuery normalises the event object to help.
There isn't an event for an individual key, you'll need to bind the keypress event and see if the keyCode is the Enter key (13):
$('#txtValue').keypress(function(e) {
if (e.keyCode == 13) {
//do stuff
e.preventDefault();
e.stopPropagation();
//-or-
//return false;
}
});
there's no event for ENTER you have to check every key and then if evt.keycode == 13 you have an ENTER
Hope this helps
You just need to add some logic to your event handler to check to see which key triggered the event:
$(function(){
$('#txtValue').keyup(function(event){
if(event.which == 13){
// enter was pressed
}
});
});

jQuery: Prevent enter key [duplicate]

This question already has answers here:
Prevent users from submitting a form by hitting Enter
(36 answers)
Closed 6 years ago.
I am trying to prevent the enter key from being put into a textarea, but it doesn't seem to work.
$('#comment').keyup(function(event) {
if (event.text.charCodeAt() == '10') {
event.preventDefault();
}
});
I have written little demonstration on jsfiddle.net, where you can try this code
Everybody has right answer :)
$('#comment').keypress(function (event) {
if (event.keyCode === 10 || event.keyCode === 13) {
event.preventDefault();
}
});
You can't cancel a keyup event. You can cancel keydown and keypress events though. In the documentation, notice that under "Event Information", "Cancels" is "No" for keyup:
keyup
keydown
keypress
Using keydown allows you to cancel far more keys than keypress, but if you don't want to cancel until after the key has been lifted, keypress is what you want. Fortunately for you, the enter key is one of the cancellable keys for the keypress event.
Use event.keyCode in the keydown event:
$('#comment').keydown(function(event) {
if(event.keyCode == 13) return false;
//carry on...
});
$('#comment').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
While the answers provided here will prevent someone from typing a carriage return, it will not prevent someone from pasting one in.
You would need to do some post processing of the text (in javascript or server-side) to remove them.
http://jsfiddle.net/we8Gm/
But the question is, why? Why not simply use <input type="text"></input> which takes care of this automatically as it is a single-line input element?
Try with .keypress and use return false;
Good luck!

Categories

Resources