Execute a function on key press if condisions are right - javascript

So the problem is... It doesn't work. And more correctly... how can i better execute those nested ifs?
document.body.onkeypress = function(e) {
e = e || window.event;
if (e.keyCode == '38') { //arrow up
}
if (e.keyCode == '40') { //arrow down
if (top == 1) {
window.setTimeout(show2, 100);
alert('2 layer works');
}
if (top == 2) {
window.setTimeout(show3, 100);
}
if (top == 3) {
window.setTimeout(show4, 100);
}
}
}
I've tried everything. Please help me...

Start with this example. It shows how to hook up the keydown event to the document body correctly. From here you should be able to modify it to add the additional logic you have in your example. Be careful to make sure external variables like top are set correctly.
function handleKeyDown(e) {
console.log('got keyDown event. e.keyCode =', e.keyCode)
}
document.body.addEventListener("keydown", handleKeyDown, false);
<p>Press a key</p>

Where do you change the top value...? Also the first if statement, if its blank like you showed us here, will throw in an error, or at least won't do anything. Why do you say e = e || window.event ..? Also, this might be just me, but don't call the functions like that. Better ( again, at least in my opinion ) to do:
document.body.addEventListener("keypress", e => {
// Get rid of that e = e || window.event, I have no clue why you'd do that.
if (e.keyCode == 38) {
// Actually give it some parameters to do here, leaving it empty will either
// throw an error or in "best" case won't do anything.
}
if (e.keyCode == 40) {
// Again, you said you did var top = 1. It will work here.
if (top == 1) {
window.setTimeout(show2, 100);
alert('2 layer works');
}
// But you dont INCREMENT the top variable anywhere, so this wont work.
if (top == 2) {
window.setTimeout(show3, 100);
}
// But you dont INCREMENT the top variable anywhere, so this wont work.
if (top == 3) {
window.setTimeout(show4, 100);
}
}
})
This question is really, really badly formatted and you haven't provided much information. Show us the error you get, use console.log all the time, it's your best friend.

Related

Is it necessary to null an onkeydown method?

My code (seen below) seems to work properly, however, I have been reading (e.g. in How can I avoid autorepeated keydown events in JavaScript?) that in some instances, onkeydown() method needs to be nulled. Why is this?
The intent of this code is to listen for a left or right arrow press (on the index file) and send a function to an iframe, which then forwards another function to another embedded iframe. There was probably a better way to do this, any input?
//Arrow key functionality
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
// right arrow
document.getElementById('CENTER').contentWindow.fwdFrame();
}
else if (e.keyCode == '37') {
// left arrow
document.getElementById('CENTER').contentWindow.bkFrame();
}
}
The iframe ('CENTER') has the following code:
//Arrow Key Functionality - Forwarded from Index
function fwdFrame() {
document.getElementById('CONTROL').contentWindow.GoNext();
}
function bkFrame() {
document.getElementById('CONTROL').contentWindow.GoBack();
}
Any help appreciated!

JS keylogger not accepting keyup correctly

I'm pretty new to JS, so I could have made some sort of silly error, but my keylogger doesn't seem to be functioning correctly. It accepts multiple keystrokes correctly, but when one is released, it recognizes both as up. Any help?
Here is my code:
var keymap = {};
onkeydown = onkeyup = function(e){
keymap[e.keyCode] = e.type == 'keydown';
if(keymap[39] && keymap[32]){ // Right+Space
jumpRight();
}
if(keymap[37] && keymap[32]){ // Left+Space
jumpLeft();
}
if(keymap[32]){ // Space
jump();
}
if(keymap[39]){ // Right
right();
}
if(keymap[37]){ // Left
left();
}
}
I'm using Google Chrome, if that helps any.
Thanks!
I think it's recognizing keystrokes correctly, because the array is being updated correctly. The problem is that your functions (left(), right(), jump(), etc.) are only firing when a keypress event happens. When you hold down a key, sometimes it will keep firing keydown events, and sometimes it won't. This causes the functions not to fire, even though your program knows that the key is being held down.
Working example (shows the array values all the time, not just on keypresses; shown array value doesn't necessarily mean the function fires):
var keymap = {};
onkeydown = onkeyup = function(e){
keymap[e.keyCode] = e.type == 'keydown';
if(keymap[39] && keymap[32]){ // Right+Space
jumpRight();
}
if(keymap[37] && keymap[32]){ // Left+Space
jumpLeft();
}
if(keymap[32]){ // Space
jump();
}
if(keymap[39]){ // Right
right();
}
if(keymap[37]){ // Left
left();
}
}
document.onkeydown=onkeydown;
document.onkeyup=onkeyup;
function jump(){}
function left(){}
function right(){}
function jumpLeft(){}
function jumpRight(){}
setInterval(function(){console.log(keymap[37]," ",keymap[32]," ",keymap[39]);},5);
Nonworking example (how it is right now, shows array values only on keypresses; shown array value == function fires):
var keymap = {};
onkeydown = onkeyup = function(e){
keymap[e.keyCode] = e.type == 'keydown';
if(keymap[39] && keymap[32]){ // Right+Space
jumpRight();
}
if(keymap[37] && keymap[32]){ // Left+Space
jumpLeft();
}
if(keymap[32]){ // Space
jump();
}
if(keymap[39]){ // Right
right();
}
if(keymap[37]){ // Left
left();
}
}
document.onkeydown=onkeydown;
document.onkeyup=onkeyup;
function jump(){console.log("jump");}
function left(){console.log("left");}
function right(){console.log("right");}
function jumpLeft(){console.log("jumpleft");}
function jumpRight(){console.log("jumpright");}
Note how in the nonworking example, the logging only happens on keydown events, which is when your functions will be called. In the "working" example, the logging happens regardless of key events, but your functions will still fail to fire, since they still happen when key events do. Here's a fully working example:
var keymap = {};
onkeydown = onkeyup = function(e){
keymap[e.keyCode] = e.type == 'keydown';
}
document.onkeydown=onkeydown;
document.onkeyup=onkeyup;
function jump(){console.log("jump");}
function left(){console.log("left");}
function right(){console.log("right");}
function jumpLeft(){console.log("jumpleft");}
function jumpRight(){console.log("jumpright");}
function main(){
if(keymap[39] && keymap[32]){ // Right+Space
jumpRight();
}
if(keymap[37] && keymap[32]){ // Left+Space
jumpLeft();
}
if(keymap[32]){ // Space
jump();
}
if(keymap[39]){ // Right
right();
}
if(keymap[37]){ // Left
left();
}
}
setInterval(main,250);
Hope this helps!
Good luck learning more JS!
P.S.: You labeled left() as "space". :P

JS two if's statement

I wrote a javascript code which if you are browsing with Firefox and if the window is resized to pop up an alert box. However, my knowledge is not enough to see where is the mistake in the code I wrote. If someone can help me I will be really grateful. Thanks in advance.
$('FirefoxChecker').ready(function() {
if (navigator.userAgent.indexOf("Firefox") > 0) && (window.onresize){
alert("Some text here");
};
});
Incorrectly formatting your conditional statement
$('FirefoxChecker').ready(function() {
if (navigator.userAgent.indexOf("Firefox") > 0 && window.onresize){
alert("Some text here");
}//; no semicolon
});
You can have as many conditions as you want in one statement for example
if( condition1 && conditio2 || condition3) { }
Your initial statement was a disconnection between eachother.
if( condition1) && (condition2) {} //is incorrect of course
YET! We can do something like this and what it does is clean the statement up or make the statement more accurate.
//group1 //group2
if( (condition1 && condition2) || (condition3 && condition1) )
1 2 2 3 3 1
I've added numbers below and they correspond to each parenthesis that it belongs to.
As others have said window.onresize is not a testable property, but you get that and hopefully can move forward on that. We can test onresize though like so
if("onresize" in window) {}
window.onresize is an event not property.
Edit: As mentioned by EasyBB in comments, onresize is a property of the window but its in initial value is null unless we define one. It expects a value to be an eventHandler which will be invoked when resize event takes place.
Try this:
window.onresize = function() {
if (navigator.userAgent.indexOf("Firefox") > 0) {
alert("Some text here");
}
};
To invoke something when resize is done, try this:
var timeOut;
window.onresize = function() {
clearTimeout(timeOut);
timeOut = setTimeout(function() {
if (navigator.userAgent.indexOf("Firefox") > 0) {
alert("Some text here");
}
}, 200);
};

Detecting left and right control keys in Javascript

I have a text input, where I need to bind an event on doing a CTRL-V. I have set a global variable named ctrl which is set to 1 whenever a keydown is fired with a which value of 17. Similarly it is made 0 when a keyup is fired with which value of 17
Problem is, there are two CTRL keys. So if I do something like: first pressing the left CTRL key, and while pressing it down, press the right CTRL key also (so that both CTRL keys are pressed now), and then I release only one of them, the keyup is fired and the variable ctrl is set to 0, even though the other CTRL key is still being pressed.
How do I fire the events such that the variable is set to 0 only when both CTRL keys are up (I don't need to exactly differentiate between them).
Update : this is now possible in modern browsers
The easiest way to detect left and right control keys in Javascript
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (event.location == 1) console.log('left ctrl');
if (event.location == 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: You have to click the inside white space when you run code snippet to activate keyboard keys. This is tested in Chrome and Safari.
There are two properties for this of keydown event.
You can differentiate left and right Ctrl by using
if ( e.location == 1 || e.keyLocation == 1 ) {
var keyPosition = 'left';
} else if ( e.location == 2 || e.keyLocation == 2 ) {
var keyPosition = 'right';
}
I don't think there is a way for that unless you write on lowlevel ... keyCode is the same for both (it is 17)
Just You can use e.ctrlKey as a way to determine if the control key was pressed.
However I read around and found one answer mentioning you could do that in IE but I did not try it from my side
you can use e.originalEvent.location instead of the global event.location
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (e.originalEvent.location === 1) console.log('left ctrl');
if (e.originalEvent.location === 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
below is your answer for three mouse keyup events. rest for mousewheel you should ask again:
/*
1 = Left Mousebutton
2 = Centre Mousebutton
3 = Right Mousebutton
*/
$(document).mousedown(function(e) {
if (e.which === 3) {
/* Right Mousebutton was clicked! */
alert("right key code 3");
}
else if(e.which === 2) {
alert("Centre key code 2");
}
else if(e.which === 1) {
alert("Left key code 1");
}
});
you can use this:
$('#inputboxinput').bind('keypress', function(e) {
if(e.keyCode==13){
// Enter pressed... do anything here...
}
});
the cross-browser way:
if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode: event.keyCode)) {
event.which = event.charCode || event.keyCode;
}

Detect double Ctrl keypress in JS

I have a custom CMS and would like to add a "shortcuts menu" triggered by the pressing of the Ctrl key twice within, say, 300 milliseconds.
I use prototype, so my starting point obviously is:
Event.observe(document, 'keypress', function(event)
{ if(event.keyCode == Event.KEY_XYZ) { show_shortcuts});
My approach at the moment would be populating a global variable with the current time in milliseconds, and checking on each keypress whether a keypress has happened less than 300 milliseconds ago.
But maybe there is a more elegant solution?
This should work. Maybe add some further checking if not some other key like Alt or Shift are pressed at the same time. Hope it is self explanatory, if not just ask and I provide clarification.
var dblCtrlKey = 0;
Event.observe(document, 'keydown', function(event) {
if (dblCtrlKey != 0 && event.ctrlKey) {
alert("Ok double ctrl");
dblCtrlKey = 0;
} else {
dblCtrlKey = setTimeout('dblCtrlKey = 0;', 300);
}
});
https://jsfiddle.net/3tc26g7x/
function doubleControlEvent() {
if (event.key === 'Control') {
timesCtrlClicked++
if (timesCtrlClicked >= 2) {
console.log('Double control')
// Double Crtl is clicked add your code here
}
setTimeout(() => (timesCtrlClicked = 0), 200)
}
}
let timesCtrlClicked = 0;
document.addEventListener('keyup', doubleControlEvent, true)

Categories

Resources