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>
Related
i have written a code :
$('*').on('keyup',function(e){
if(e.keyCode == 13){
$(this).trigger('click');
}
});
the above code works fine until jquery dialog. Apparently whenever i hit an enter key in the dialog. it sort of like bubbles up the event.
i have 2 dialogs. 1st is the confirm dialog and 2nd is the message dialog. when i hit yes it will pop up the message dialog and when i hit ok on the message dialog the confirm dialog will open again.
i tried like this :
$('*').not('.ui-button').on('keyup',function(e){
if(e.keyCode == 13){
$(this).trigger('click');
}
});
this is for the exclusion of the ui-buttons for the enter events. it did not work. Any help would be appreciated. thanks
EDIT :
note that i call the dialogs to open using a link. i wonder if that link is focused when i hit enter so it calls the dialog again when i hit enter on the message dialog.
Why not cancel its event by using off?
$('*').on('keyup',function(e){
if(e.keyCode == 13){
$(this).trigger('click');
}
}).find(".ui-buttons").off('keyup'); // this unbinds the event so it won't trigger
It might be that the ui buttons are not created when the handlers are registered.
One approach you can do is to register a single handler to the document object, then see whether the actual target is a ui-button like
$(document).on('keyup', function (e) {
var $target = $(e.target);
if ($target.closest('.ui-button').length) {
return;
}
if (e.keyCode == 13) {
$target.trigger('click');
}
});
use this code, this code exclude .ui-button element and inner elements of .ui-button class
$('body').on('keyup',function(e){
if(!$(e.target).closest('.ui-button').length && e.keyCode == 13){
$(e.target).trigger('click');
}
});
I admit I'm not a big fan of global bindings, especially because of these problems. I find it better to specify the types and/or location of the elements I want to bind the event to.
One of the reasons is this event bubbling that sadly does not behave the same way in all browsers.
My suggestion is to bind the event only to the desired elements and add e.stopPropagation() to the called function(s).
I know this is not the answer you were looking for but I believe you should consider this method for being more specific (and more reliable).
I fixed the problem by blurring the link that i clicked to open the dialog.
something like :
$('.links').find('a').on('click',function(){
$(this).blur();
});
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
I'm trying get my <a> tag triggered when the user press on the "enter" key. (onkeypress).
my <a> tag:
<a href="javascript:search()" onkeypress="return runScript(event)">
this is my javascript :
function runScript(e)
{
if (e.keyCode == 13) {
alert("dssd");
return false;
}
}
I dont know whats messed up ?
its work for me
Open in new window using javascript
javaScript
window.runScript = function (e) {
if (e.keyCode == 13) {
alert('ss');
return false;
}
else {
return true;
}
}
window.search = function () {
alert('s');
}
live demo : fiddle
Write your html as given below. Note the property tabindex which makes the a tag focusable in certain browsers.
<a id="link" href="http://google.com" onkeydown="runScript(event)" tabindex="1">I am a link</a>
If you need an autofocus on load, you can use the jQuery function focus as shown below.
$(document).ready(
function(e){
$("#link").focus();
}
);
Then your function
function runScript(e){
if(e.keyCode == 13){
alert("pressed enter key");
}
}
you have to call e.preventDefault(); (or return false in some browsers) if you want to prevent the link load the link in href.
function runScript(e){
e.preventDefault();
if(e.keyCode == 13){
alert("pressed enter key");
}
return false;
}
see a demo here:
http://jsfiddle.net/diode/hfJSn/9/show press enter key when the page is loaded
The ENTER key actually triggers the onclick event:
<a href="#" onclick="alert('hello!');">
This means that your search() function inside the href will execute before the onkeypress event.
That works in my browser, though I suspect it's not the way to achieve what you actually want to do... (maybe?)
Number one, you probably don't want it to "return" anything, so you can just do onkeypress="runScript(e)" and it'll run. If that function does return a value, it's not gonna go anywhere...
Number two, it's kinda rare that a keydown event would fire on an anchor (<a>) element, unless of course the user tabs through the other elements 'till it has focus and then presses a key (usually the browser will "highlight" the element that currently has keyboard focus, if it's not just the whole page). Are you wanting your script to run when someone presses enter after typing in a search box or something? if so, you probably want to listen for the event on the search box itself, so add it as that element's onkeydown attribute (for example: <input id="mySearchBox" onkeydown="runScript(e)">) if you just want it to run whenever the user presses enter, regardless of focus or typing text into any particular field, just do as edmastermind29's comment said and add the event listener to the whole document.
Have you tried adding this to your script?
document.onkeypress = runScript;
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
}
});
});
I've got a simple Listbox on a HTML form and this very basic jQuery code
//Toggle visibility of selected item
$("#selCategory").change(function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
});
The change event fires fine when the current item is selected using the Mouse, but when I scroll through the items using the keyboard the event is not fired and my code never executes.
Is there a reason for this behavior? And what's the workaround?
The onchange event isn't generally fired until the element loses focus. You'll also want to use onkeypress. Maybe something like:
var changeHandler = function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
}
$("#selCategory").change(changeHandler).keypress(changeHandler);
You'll want both onchange and onkeypress to account for both mouse and keyboard interaction respectively.
Sometimes the change behavior can differ per browser, as a workaround you could do something like this:
//Toggle visibility of selected item
$("#selCategory").change(function() {
$(".prashQs").addClass("hide");
var cat = $("#selCategory :selected").attr("id");
cat = cat.substr(1);
$("#d" + cat).removeClass("hide");
}).keypress(function() { $(this).change(); });
You can chain whatever events you want and manually fire the change event.
IE:
var changeMethod = function() { $(this).change(); };
....keypress(changeMethod).click(changeMethod).xxx(changeMethod);
The behavior you describe, the change event triggering by keyboard scrolling in a select element, is actually an Internet Explorer bug. The DOM Level 2 Event specification defines the change event as this:
The change event occurs when a control
loses the input focus and its value
has been modified since gaining focus.
This event is valid for INPUT, SELECT,
and TEXTAREA. element.
If you really want this behavior, I think you should look at keyboard events.
$("#selCategory").keypress(function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 38 || keyCode == 40) { // if up or down key is pressed
$(this).change(); // trigger the change event
}
});
Check a example here...
I had this problem with IE under JQuery 1.4.1 - change events on combo boxes were not firing if the keyboard was used to make the change.
Seems to have been fixed in JQuery 1.4.2.
$('#item').live('change keypress', function() { /* code */ });