Onkeydown not working javascript - 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);

Related

How can I disable repetition of an eventListener keydown event in plain JavaScript

I am trying to stop a keydown event from repeating for a game. I am unable to use libraries due to it being part of a school project. I have tried most of the answers I can access but they don't work for my code, I also can't use MDN because it's blocked. Here is the code
window.addEventListener("keydown", function (e){
if (e.keyCode == 32) {
accelerateBy = -0.5
accelerate()
}
});
You may have to use some variable to save the state of you key. Here's an example:
let isKeyDown = false;
document.addEventListener("keydown", (event) => {
if (event.keyCode == 32) {
if (isKeyDown) { return; } // If key was already down, don't do anything
isKeyDown = true;
// do your stuff here
}
});
document.addEventListener("keyup", (event) => {
if (event.keyCode == 32) {
isKeyDown = false;
}
});

javascript freezing tabs, and input

I am making a JavaScript onkeypress function.
function report() {
while (1 == 1) {
window.onkeypress = function(event) {
/* from this point down, keylog functions. */
// above is a variable
if (event.keyCode == 32) {
console.log("Spacebar._rep")
}
if (event.keycode == 33) {
console.log("escalation-Mark._rep")
}
if (event.keycode == 34) {
console.log("quotation-Mark._rep")
}
if (event.keycode == 35) {
console.log("hashtag._rep")
}
if (event.keycode == 36) {
console.log("dollar-Sign._rep")
}
if (event.keycode == 37) {
console.log("percent-Symbol._rep")
}
if (event.keycode == 38) {
console.log("pi")
}
}
}
}
report()
whenever i run this code, however it freezes all forms of input, i can still scroll, open tabs, and click. I cannot close the tab, reload, or change the JavaScript code. I have tried it with and without variables, and i have tried modifying it. It works absolutely fine when their is only one key function, but once i add several it freezes.
I have de-dented, and indented nothing has worked.
I have checked out a few other similar questions, which said to do things like remove variable, and i did that and it still freezes.
You're creating an infinite loop which freezes that tab.
while (1 == 1) {
//infinite loop
}
Instead of doing that, just attach a listener to the window that fires a callback each time the event occurs:
window.addEventListener('keypress', function (e) {
console.log(e)
});
The onkeypress property sets and returns the onKeyPress event handler
code for the current element.
As you current element is window when you run report the event listener will listen to any keypress, there is no really need of a while statement, it actually make freeze you app.
function report() {
window.onkeypress = function(event) {
if (event.keyCode == 32) {
console.log("Spacebar._rep")
}
if (event.keycode == 33) {
console.log("escalation-Mark._rep")
}
if (event.keycode == 34) {
console.log("quotation-Mark._rep")
}
if (event.keycode == 35) {
console.log("hashtag._rep")
}
if (event.keycode == 36) {
console.log("dollar-Sign._rep")
}
if (event.keycode == 37) {
console.log("percent-Symbol._rep")
}
if (event.keycode == 38) {
console.log("pi")
}
}
}
report()
1
It is freezing because while (1==1) is running infinitely, you should not write you code like this. It is blocking the browser
window.onkeypress = function(event) {
/* from this point down, keylog functions. */
// above is a variable
if (event.keyCode == 32) {
console.log("Spacebar._rep")
}
if (event.keycode == 33) {
console.log("escalation-Mark._rep")
}
if (event.keycode == 34) {
console.log("quotation-Mark._rep")
}
if (event.keycode == 35) {
console.log("hashtag._rep")
}
if (event.keycode == 36) {
console.log("dollar-Sign._rep")
}
if (event.keycode == 37) {
console.log("percent-Symbol._rep")
}
if (event.keycode == 38) {
console.log("pi")
}
}
this is all that is needed, the code will be "asynchronously" called
Try removing "while (1 == 1)". It seems like it doesn't leave that while-loop.

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

How to fire one function for two separate events in js?

I have 2 events, a keydown and a click. I would like to put them into a single function and when the function is called, whichever event was fired would do what it's supposed to.
Example:
var close = function () {
$('.alert').remove();
};
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
//27 = ESC
close();
}
});
$('.alertBG').on('click', function () {
close();
});
I can't think of a way to get the document and .alertBG parts to play nicely. (Fiddle)
Don't. Your functions are too different. You have already factored the reusable parts of them out into a close function that you call from both. This is the best way to do it.
If you really wanted to, then you would have to bind a click/keydown handler to document and test the type of event and the element.
$(document).on("keydown click", function (event) {
if (
(event.type === "keydown" && event.keyCode === 27) || (event.type === "click" && (
$(event.target).is(".alertBG") || $(event.target).parents(".alertBG").length))) {
close();
}
});
As you can see, it's much cleaner just to bind your event handlers separately when there are so many differences between them.
Do you mean something like this?
function handler(event) {
if(event.type === "click") {
close();
} else if(event.type === "keydown") {
if (event.keyCode === 27) {
//27 = ESC
close();
}
}
}
$(document).on('keydown', handler);
$('.alertBG').on('click', handler);
Anything like this ?
function myFunc(method){
if(method == "one"){
// do anything
}
else if(method == "other"){
// do other thing
}
}
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
myFunc("one");
}
});
$('.alertBG').on('click', function () {
myFunc("other");
});

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

Categories

Resources