clicking a button with a keyboard - javascript

lets say I have a button like this:
<input id="a" type="button" value="A" />
and I want it so that if I press the "a" key on the keyboard, it visually acts as though I am clicking the button with the mouse.
Is there a way to do that?

document.onkeydown = function (evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 65) {
document.getElementById("a").click();
// Your function here.
}
};
for other keycodes refer
Keycodes

Have a look at HTML5's globalaccesskey:
http://www.w3schools.com/tags/att_global_accesskey.asp
** EDIT **
Or if you are looking for a pure javascript way, you could try this:
document.onkeypress = textsizer;
function textsizer(e){
var evtobj=window.event? event : e;
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey=String.fromCharCode(unicode);
if (actualkey=="e"){
document.getElementById('a').click();
}
}

This should work: (Assumes JQuery)
$(document).keyup(function (event) {
if (event.which == 65) { // "A" key
$('#a').click();
}
});

Related

Escape key pressing not run keydown event [duplicate]

Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode

Key HIT/press event

I want to take key press event, ut this is not on specific field, its on page/window.
Example:
While doing automation, on web page I have short-cut key suppose M (keyboard key). So how should I achieve this? If it can be achieved by inserting a JavaScript then how can I write it? I'm beginner in JavaScript.
Using jquery you can do this as follow.
$(document).keydown(function(e){
if (e.keyCode == 77) {
alert( "M key pressed" );
}
});
Try the following code:
<script>
function keyEvent (e) {
if (!e)
e = window.event;
if (e.which) {
keycode = e.which;
} else if (e.keyCode) {
keycode = e.keyCode;
}
if(keycode == 77){
alert('Hi!');
}
}
document.onkeydown = keyEvent;
</script>
As you want it on the window I would add a eventListener function direct on the window object like this. You can google the keyCode if you want to change keyCode. This works with and without jQuery library :) http://jsfiddle.net
window.addEventListener('keypress', function(e) {
e = e || window.event;
switch(e.which) {
case 77:
if (e.ctrlKey) {
alert( "M + ctrlKey is down" );
// do some here
}
else {
alert("M is down")
}
break;
}
}, false);

How to detect "tab keypress" when focus is at a button using JavaScript

I'm just wondering if any of you done an onkeypress on a button.
my button is like this:
asp:Button ID="btnClear" runat="server" Text="Clear" onkeypress="return goToFirst();"/>
the javascript:
function goToFirst(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
alert(charCode);
if (charCode = 9 ) {
document.getElementById('txtFirstName').focus();
document.getElementById('txtFirstName').select();
}
return false;
My goal is to detect the tab keypress on a button and set the focus on the specified textbox when tab is pressed.
The problem is that the onkeypress event does not fire when tab key is pressed. other keys like numbers and letters fires the event, but not tab.
Is there a solution to my goal?
Thanks in advance!
use onkeydown. here's a demo
<input ID="btnClear" onkeydown="return goToFirst();"/>
.
function goToFirst(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
alert(charCode);
if (charCode == 9 ) {
document.getElementById('txtFirstName').focus();
document.getElementById('txtFirstName').select();
}
return false;
};
I solved a similar problem using ev.stopPropagation() and ev.preventDefault() after show the input.

How do i call a js function on pressing enter key

I'd like to know how I can initiate a javacsript function when pressing the enter key. I'm trying to create a function called handleEnter(event, fn).
I want to use the function on an input field eg:
onkeypress="return handleEnter(event, update_field(this));
For your function called onkeypress, check the event's .keyCode or .which value, and see if it is equal to 13.
function handleEnter(e, func){
if (e.keyCode == 13 || e.which == 13)
//Enter was pressed, handle it here
}
IIRC, IE uses event.which, and Firefox will use e.keyCode to see which key was pressed.
I think I've solved it.
On the input field I've got:
<input onkeypress="return handleEnter(event, update_field, this, 'task');" type="text" />
For my function I've got:
function handleEnter(e, callback, obj, field){
if(e){
e = e
} else {
e = window.event
}
if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}
if(keycode == 13) {
var tstid = $(obj).parent().find('input[type=hidden]').val();
callback.apply(this, [field, $(obj).val(), tstid ]);
}
}
and it seems to be working fine now.
You can try this shorthand
<input type=”text” onKeydown=”Javascript: if (event.keyCode==13) Search();”>
<input type=”button” value=”Search” onClick=”Search();”>
From http://www.techtamasha.com/call-javascript-function-on-pressing-enter-key/25

element onkeydown keycode javascript

I am using this code snippet to add KeyDown event handler to any element in the html form
for(var i=0;i<ele.length;i++)
{
ele[i].onkeydown = function()
{
alert('onkeydown');
}
}
How can I know which key has been pressed on keydown event? I try this
for(var i=0;i<ele.length;i++)
{
ele[i].onkeydown = function(e)
{
alert(e.KeyCode);
}
}
but it is not working, why?
Thanks a lot
This is the code I use for this problem. It works in every browser.
//handle "keypress" for all "real characters"
if (event.type == "keydown") {
//some browsers support evt.charCode, some only evt.keyCode
if (event.charCode) {
var charCode = event.charCode;
}
else {
var charCode = event.keyCode;
}
}
For detecting Enter, you could use the following code, which will work in all mainstream browsers. It uses the keypress event rather than keydown because Enter produces a printable character:
ele[i].onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 13) {
alert("Enter");
// Do stuff here
}
};
I used this:
function check(){
if (event.keyCode == 32){
alert("Space is pressed");
}
}
and in my body tag: onKeyPress="check()"
It is keyCode, not KeyCode.

Categories