Javascript - How to create a keypress event? - javascript

I've looked on the internet for this and all I can find are depreciated functions so before posting please check to make sure that the code you suggest isn't depreciated.
I've found this and tried it:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
$(document).ready(function () {
var x = new KeyboardEvent("FormatCode", deprectiatedArgument);
});
But after further inspection the KeyboardEventInit is depreciated.
I would like to create an event on pres of the CTRL + K keys.

You have a specific key code for every button on the keyboard.
All of them are here http://keycode.info/.
$(document).keyup(function(e) {
if (e.keyCode === 13) function(); // enter
if (e.keyCode === 27) function(); // esc
});

Here's a vanilla JS solution to detect a CTRL + k keypress event:
UPDATED to also trigger the event.
document.addEventListener("keypress", function(e) {
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 11 || e.keyCode == 75)) {
alert("ctrl+k!");
}
});
document.getElementById("trigger").addEventListener("click", function(){
//trigger a keypress event...
var e = document.createEvent('HTMLEvents');
e.initEvent("keypress", false, true);
e.ctrlKey = true;
e.keyCode = 75;
document.dispatchEvent(e);
});
Press <kbd>ctrl+k</kbd> or
trigger the event

you can use a library called shortcut.js .. here is a link to their source code for downloading:
http://www.openjs.com/scripts/events/keyboard_shortcuts/shortcut.js
then run ur code by making this function:
shortcut.add("Ctrl+K",function() {
alert("Hi there!");
});
and here is the documentation : http://www.openjs.com/scripts/events/keyboard_shortcuts/
hope that can help.

$(document).ready(function () {
var bool = false;
$(document).keydown(function (e) {
if (e.keyCode === 17) {
bool = true;
}
if (bool == true && e.keyCode == 75) {
alert("");
}
});
$(document).keyup(function (e) {
if (e.keyCode === 17) {
bool = false;
}
});
});
This is how me and a friend got it working

Related

How I can detect Key "Enter" on "input" event? [duplicate]

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);
}
}

Add keypress or eventlistener to input, "TypeError: ...addEventListener is not a function"

I'm working on a form where I do not want enter/return to submit the form so I used a function like this.
$('[name="form"]').keypress(function(e) {
var charCode = e.charcode || e.keyCode || e.which;
if (charCode === 13) {
e.preventDefault();
return false;
}
});
That works, but now I want to assign the enter/return to perform functions on two inputs on the form. I'm totally stuck.
To get the inputs I've tried vanilla js calling by id, jQ calling by id and then a mixer of the two with variables. I've also tried .keypress, .keydown, .keyup instead of the attachEventListener method. No matter what I do, I get this error in console.
"TypeError: ...addEventListener is not a function" (or keypress, keydown etc.)
I've also researched a good deal but can't find any solution. I appreciate any suggestions.
Here is this block of code in it's current form that's giving the trouble.
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');
yelpInput.addEventListener("keydown", function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
// Google
googleInput.addEventListener("keydown", function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
Thanks
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');
yelpInput.keydown(function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
// Google
googleInput.keydown(function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});
yelpInput is jQuery wrapped object which does not have addEventListener method.
Use .on to attach event-handler on jQuery wrapped object or yelpInput[0].addEventListener/yelpInput.get(0).addEventListener to attach event using JavaScript as yelpInput[0] will be an DOMElement not jQuery-wrapped object.
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');
yelpInput.on("keydown", function(e) {
//-----^^^
if (e.keyCode === 13) {
alert('do stuff!');
}
});
googleInput.on("keydown", function(e) {
//-------^^^
if (e.keyCode === 13) {
alert('do stuff!');
}
});

having problems binding javascript to a submit button

I'm having a problem binding this script to a submit button...
$('input').on('keydown', function(event) {
var x = event.which;
if (x === 13) {
event.preventDefault();
}
});
I've done it before but it's been a long time and the examples on the web are not doing it for me. Thanks :)
jQuery(function($) { // DOM is now ready
// your code here
});
should do the trick.
https://learn.jquery.com/using-jquery-core/document-ready/
$(document).ready(function(){
$('input').on('keydown', function(e) {
if (e.keyCode == 13 || e.which == 13) {
e.preventDefault();
}
});
})
Please try this
or you can try this code by using IIFE
(function($) {
$('input').on('keydown', function(e) {
if (e.keyCode == 13 || e.which == 13) {
e.preventDefault();
}
});
})(jQuery);

jQuery keyboard activate a button

this is what I got so far
http://jsfiddle.net/qEKfg/
It's two buttons that activate on click and look like keyboard keys.
I'm trying to make it where they will only activate (animate) on a keyboard press of the related keys (CTRL and D)
This will make an 'animated buttons' effect for bookmarking my website, because CTRL+D is the hotkey to bookmark a page.
But I don't know how to set it up to work with keyboard keys in html or jQuery
if some could help I would be really REALLY grateful
The following should work for you. However, note that due to the window losing focus, I've added in a timer to release the on-screen 'buttons' after 5 seconds, as the window losing focus at that specific time prevents the keyup event from firing.
$(document).ready(function() {
var keys = [];
$(window).on('keydown keyup', function(e) {
if (e.type == "keydown") {
if (e.keyCode == 17 || e.keyCode == 91) {
$("a.a_demo_two:contains('CTRL')").addClass("active");
keys[0] = e.keyCode;
}
else if (e.keyCode == 68) {
$("a.a_demo_two:contains('D')").addClass("active");
keys[1] = 68;
};
if ((keys[0] == 17 || e.keyCode == 91) && keys[1] == 68) {
setTimeout(function() {
$('a.a_demo_two').removeClass("active");
}, 5000);
}
}
else {
if (e.keyCode == 17 || e.keyCode == 91) {
$("a.a_demo_two:contains('CTRL')").removeClass("active");
}
else if (e.keyCode == 68) {
$("a.a_demo_two:contains('D')").removeClass("active");
}
keys = [];
}
});
});​
DEMO
Basically you just put handler on keydown and keyup events and trigger whatever you want.
Something like that
$('body').on('keydown', function(e) {
console.log(e)
if (e.ctrlKey) $('.a_demo_two').trigger('mousedown')
if (e.keyCode === 100) $('.a_demo_two').trigger('mousedown')
});
$('body').on('keyup', function(e) {
console.log(e)
if (e.ctrlKey) $('.a_demo_two').trigger('mouseup')
if (e.keyCode === 100) $('.a_demo_two').trigger('mouseup')
});
​

How to detect escape key press with pure JS or jQuery?

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

Categories

Resources