Disable a key press event through JavaScript - javascript

I need to disable shift keypress event in my site by using JavaScript or any other method.
Below is my code:
$(document).ready(function() {
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) {
keycode = window.event.keyCode;
}
else if (e) {
keycode = e.which;
}
//alert(keycode);
if (keycode == 16) {
alert(keycode);
return false;
}
}
});

// bind an event listener to the keydown event on the window
window.addEventListener('keydown', function (event) {
// if the keyCode is 16 ( shift key was pressed )
if (event.keyCode === 16) {
// prevent default behaviour
event.preventDefault();
return false;
}
});

http://api.jquery.com/keypress/
In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.
Try this
$('#target').keydown(function(event) {
if (event.shiftKey) {
event.preventDefault();
}
}

document.onkeydown = function (e) {
var e = e || event;
if (e.shiftKey === true) {
return false;
}
};

You may try this:
jQuery(document).keydown(function(e){
if(e.which === 16) {
e.preventDefault();
return;
}
console.log(e.which);
});
See demo.
Use Firebug and check console output.

Related

Javascript - How to create a keypress event?

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

Onkeydown not working javascript

Here is my code
document.onkeydown = function (a) {
if (a.which == 13) {
alert("Not Anymore");
}
}
document.onkeydown = function (b) {
if (b.which == 65) {
auto();
}
}
document.onkeydown = function (c) {
if (c.which == 83) {
auto2();
}
}
Only the last snippet works can someone explain why this is happening
check my website and you can see it isnt working when you press a but when you press b it is
Thanks, I appreciate the help and feedback
You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.
You can use this
document.onkeydown = function (e) {
if (e.which == 13) {
alert("Not Anymore");
} else if (e.which == 65) {
auto();
} else if (e.which == 83) {
auto2();
}
};
Also, use addEventListener instead of onkeydown.
document.addEventListener('keydown', function (a) {
if (a.which == 13) {}
...
}, false);

javascript avoid enter key press

I'm trying to detect an Enter key press event when a button has been clicked.
I'm new in javascript and don't know the good way to go...
HTML:
<div id="div"> Only execute javascript on click, not enter key press </div>
JAVASCRIPT:
$("#div").click(function () {
/* IF ENTER KEY PRESSED, RETURN FALSE */
$("#div").keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
alert('clicked');
}
});
/* Div has been clicked, continue code... */
});
This doesn't work...
Maybe there is a better way:
$("#div").MOUSE_CLICK_EVENT(function () {});
You need to stopPropagation like:
$('#div').keydown(function(event){
if (event.which == '13') {
event.preventDefault();
event.stopPropagation();
}
});
stopPropagation: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
As others have noted, you need stopPropagation in addition to preventDefault, and you should be listening for the keydown event rather than keypress.
The pure JavaScript way to do this is:
document.getElementById('div').onkeydown = function (evt) {
if (evt.which === 13) {
evt.preventDefault();
evt.stopPropagation();
return false;
}
};
document.getElementById('div').onclick = function (evt) {
// do whatever you want here
};
try this if still needs anybody. Quick solution.
$("form").keypress(function(e) {
//Enter key
if (e.which == 13) {
return false;
}
});
Also you need to consider 3 key events: keydown, keypress and keyup.
$("#ID").keydown (function (e) {
if ( e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$("#ID").keyup (function (e) {
if (e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$("#ID").keypress (function (e) {
if (e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});

keydown Event to override return key does not work in Firefox

I have the following simple javascript code, which handles the Return Key, I don't want to submit the form when the return key is pressed in the textbox.
All this works fine, but in Firefox, if i show an alert message, then it stops working and the form starts getting submitted, whereas the exact code without alert message works fine and stops the form from being submitted. I dont understand why alert is spoiling the party..
$("document").ready(function () {
$("#input1").keydown(OnKeyDown);
});
function OnKeyDown(e) {
if (e.keyCode == 13) {
// alert('this will fail'); // Adding alert makes the form submit
stopBubble(e);
return false;
}
}
function stopBubble (e) {
// If an event object is provided, then this is a non-IE browser
if (e && e.stopPropagation)
// and therefore it supports the W3C stopPropagation() method
e.stopPropagation();
else
// Otherwise, we need to use the Internet Explorer
// way of cancelling event bubbling
window.event.cancelBubble = true;
}
<input type="text" id="input1" value="">
I don't really know if the event is normalized or not. But this is how I have to do it for it to work in all browsers:
$(whatever).keypress(function (e) {
var k = e.keyCode || e.which;
if (k == 13) {
return false; // !!!
}
});
jQuery normalizes this already, you can just do:
$(document).ready(function () {
$("#input1").keydown(OnKeyDown);
});
function OnKeyDown(e) {
if (e.which == 13) { //e.which is also normalized
alert('this will fail');
return false;
}
}
When you do return false from a handler, jQuery calls event.preventDefault() and event.stopPropgation() internally already. You can also do the anonymous function version:
$(function () {
$("#input1").keydown(function() {
if (e.which == 13) return false;
});
});
textBox.onkeydown = function (e) {
e = e || window.event;
if (e.keyCode == 13) {
if (typeof (e.preventDefault) == 'function') e.preventDefault();
if (typeof (e.stopPropagation) == 'function') e.stopPropagation();
if (typeof (e.stopImmediatePropagation) == 'function') e.stopImmediatePropagation();
e.cancelBubble = true;
return false;
}
}

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