Am I using keyup correctly? - javascript

This is an excerpt from a js file
$searchBox.keyup(function(event) {
if (event.keyCode === 13) { //enter
if(currentResult > -1) {
var result = $searchResults.find('tr.result a')[currentResult];
window.location = $(result).attr('href');
}
} else if(event.keyCode === 38) { //up
if(currentResult > 0) {
currentResult--;
renderCurrent();
}
} else if(event.keyCode === 40) { //down
if(lastResults.length > currentResult + 1){
currentResult++;
renderCurrent();
}
} else {
var query = $searchBox.val();
if (lastQuery !== query) {
currentResult = -1;
if (query.length > 2) {
self.search(query);
} else {
self.hideResults();
}
if(self.hasFilter(getCurrentApp())) {
self.getFilter(getCurrentApp())(query);
}
}
}
});
This means that it should only perform the action if the "Enter", "Up" or "Down" keys are pressed, right? Because the search start happening as soon as any key is pressed.
I also tried changing searchBox.keyup to searchBox.change but that messed up how something else was working.

Related

moving two pong game paddles at the same time

I have been frustrated with making a pong game. I have two paddles that I can move separately and freely as required but I miss something and they can't move at the same time as I want, it's a multiplayer game, two opponents press different keyboard keys at the same time, but something's missing in my code!
function leftPaddleMoveUp() {
leftTopLenght = leftPaddle.getBoundingClientRect().top;
if (Math.floor(leftTopLenght) === 100) {
return NaN;
} else {
leftPaddle.style.top = leftPaddleTopUp + leftPaddleTopDown + "px";
leftPaddleTopUp -= 20; // Speed
}
}
function leftPaddleMoveDown() {
leftTopLenght = leftPaddle.getBoundingClientRect().top;
if (Math.floor(leftTopLenght) === 660) {
return NaN;
} else {
leftPaddle.style.top = leftPaddleTopUp + leftPaddleTopDown + "px";
leftPaddleTopDown += 20; // Speed
}
}
function rightPaddleMoveUp() {
rightTopLenght = rightPaddle.getBoundingClientRect().top;
if (Math.floor(rightTopLenght) === 100) {
return NaN;
} else {
rightPaddle.style.top = rightPaddleTopUp + rightPaddleTopDown + "px";
rightPaddleTopUp -= 20; // Speed
}
}
function rightPaddleMoveDown() {
rightTopLenght = rightPaddle.getBoundingClientRect().top;
if (Math.floor(rightTopLenght) === 660) {
return NaN;
} else {
rightPaddle.style.top = rightPaddleTopUp + rightPaddleTopDown + "px";
rightPaddleTopDown += 20; // Speed
}
}
document.addEventListener("keypress", (event) => {
// PlayerOne&LeftSide
if (event.keyCode === 83 /*azerty & qwerty*/) {
leftPaddleMoveUp();
} else if (
event.keyCode === 87 /*azerty*/ ||
event.keyCode === 90 /*qwerty*/
) {
leftPaddleMoveDown();
}
// PlayerTwo&RightSide
else if (event.keyCode === 38 /*UpperArrow*/) {
rightPaddleMoveUp();
} else if (event.keyCode === 40 /*LowerArrow*/) {
rightPaddleMoveDown();
}
});
Is there is any method or function to accomplish this task?
You should use keydown and keyup events, and store the currently pressed keys inside an array.
const currentKeysDown = []
document.addEventListener("keydown", (event) => {
if (!currentKeysDown.includes(event.keyCode)) {
currentKeysDown.push(event.keyCode)
}
console.log(currentKeysDown)
movePaddles()
})
document.addEventListener("keyup", (event) => {
currentKeysDown.splice(currentKeysDown.indexOf(event.keyCode), 1)
console.log(currentKeysDown)
movePaddles()
})
function movePaddles() {
// PlayerOne&LeftSide
if (currentKeysDown.includes(83) /*azerty & qwerty*/ ) {
leftPaddleMoveUp();
} else if (
currentKeysDown.includes(87) /*azerty*/ ||
currentKeysDown.includes(90) /*qwerty*/
) {
leftPaddleMoveDown();
}
// PlayerTwo&RightSide
if (currentKeysDown.includes(38) /*UpperArrow*/ ) {
rightPaddleMoveUp();
} else if (currentKeysDown.includes(40) /*LowerArrow*/ ) {
rightPaddleMoveDown();
}
}
function leftPaddleMoveUp() {
console.log('Player1 moves UP')
}
function leftPaddleMoveDown() {
console.log('Player1 moves DOWN')
}
function rightPaddleMoveUp() {
console.log('Player2 moves UP')
}
function rightPaddleMoveDown() {
console.log('Player2 moves DOWN')
}

Simple move javascript game

what wrong with my code
function move(x,y)
{
setInterval(function()
{
gameArea.clear();
gamePiece.x += x;
gamePiece.y += y;
gamePiece.update();
}, 100);
}
document.getElementsByTagName('body')[0].onkeyup = function(e)
{
var myInterval;
if(e.keyCode == 37)
{
move(10,0);
}
else if(e.keyCode == 38)
{
move(0,-10);
}
else if(e.keyCode == 39)
{
move(-10,0);
}
else if(e.keyCode == 40)
{
move(0,10);
}
}
This produce output i'm not expected, and the object can't move correctly.
Please help me to fixed this.

Javascript not running in chrome app in mobile?

I have a web application that has to do with key pressing. It is functioning well across all browsers except for Chrome in mobile.
Here is the javascript code:
function O000OOO(e) {
var O0000O0;
if (window.event) {
if (window.event.type == "keypress") {
O00OO00 = -1
}
if (window.event.type == "keypress") {
O00OO00 = window.event.keyCode
}
if (parseInt(O00OO00) > 0) {
O0000O0 = O00OO00
} else {
O0000O0 = window.event.keyCode
}
} else {
if (e.type == "keypress") {
O00O0OO = e.which;
O00OO00 = -1
}
if (e.type == "keypress") {
O00OO00 = e.which
}
if (parseInt(O00OO00) > 0) {
O0000O0 = O00OO00
} else {
if ((parseInt(O00O0OO) > 0) && (e.which < 1)) {
O0000O0 = O00O0OO
} else {
O0000O0 = e.which
}
}
}
return (parseInt(O0000O0))
}
and 000000 is a string.
Does anyone have a solution for this problem?
I think you should be using the beforeinput event rather then keypress as it looks like keypress is depreciated so may not be supported. Have a look at this from w3:
https://www.w3.org/TR/uievents/#determine-keypress-keyCode
They specify partway through that:
Authors SHOULD use the beforeinput event instead of the keypress
event
So that is pretty clear.

Number in textfield should be autoformatted only after user clicks outside the textbox?

I have a problem. Basically, what happens in my case is that the numbers in my textbox are autoformatted as I type. I don't want this to happen. What I want is that the numbers should be autoformatted only when the user clicks outside the textbox.
In my input tag I have :
onkeyup="format(event, this);"
My javascript function is :
function format(e, obj) {
if (e.keyCode == 36) {
press1(obj);
}
if (e.keyCode == 13) {
return false;
}
if ((e.keyCode <= 34) || (e.keyCode >= 46 && e.keyCode < 58) || (e.keyCode >= 96 && e.keyCode <= 105)) { // //alert(e.keyCode);
obj.value = CommaFormatted(obj.value);
} else {
if (e && e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
return false;
}
}
where the press1 function is:
function press1(textControlID) {
var text = textControlID;
if (text.getAttribute("maxlength") == text.value.length) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
return true;
}
if (text != null && text.value.length > 0) {
if (text.createTextRange) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
} else if (text.setSelectionRange) {
var textLength = text.value.length;
text.setSelectionRange(textLength, textLength);
}
}
}
I really hope this could be solved. Please!
You could change onkeyup to onblur, which is the event that gets fired when the control loses focus - clicking out of it.
The onkeyup event fires with every keypress.

Snake script is not passing values to variable

So here is my snake script -
http://jsfiddle.net/6bKHc/24/
I started to create a snake game, but basically move(top), move(bottom) e.c. is not working. Any ideas why? I understand that I can't pass the elements to variable like this, so maybe you could show me how to do that correctly?
Ok cleared syntax and took a look at errors this should get you started
$(document).keydown(function(event){
var move, inter;
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
if(dir == 'top') {
snake.stop().animate({"top": "+=5px"});
}
if(dir == 'bottom') {
snake.stop().animate({"top": "-=5px"});
}
if(dir == 'left') {
snake.stop().animate({"left": "+=5px"});
}
if(dir == 'right') {
snake.stop().animate({"top": "-=5px"});
}
}, 500);
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
}; });​
fiddle
Couple of obvious additions to make:
boundary checking
smoothness of animation.
To make it work you will have to moodify your code like follows :
$(document).keydown(function() {
var inter;
return function(event) {
var move, prevDirection;
clearInterval(inter);
inter = setInterval(move = function(direction) {
var value, prop;
switch (direction || prevDirection) {
case "top":
prop = "top";
value = -5;
break;
case "bottom":
prop = "top";
value = 5;
break;
case "left":
prop = "left";
value = -5;
break;
case "right":
prop = "left";
value = 5;
break;
}
if (direction) prevDirection = direction;
$(".snake").css(prop, $(".snake").position()[prop] + value);
}, 500);
if (event.which == 40) {
move('bottom');
} else if (event.which == 39) {
move('right');
} else if (event.which == 37) {
move('left');
} else if (event.which == 38) {
move('top')
};
}
}());​
​
http://jsfiddle.net/6bKHc/42/

Categories