JavaScript move object - javascript

i have a script for move DOM object, but it doesn't work, i think troubles in my keydown countruction where im trying to add/subtract and nothing happens. Can somebody explain why?
mouse.setAttribute('tabindex', '0')
alert(typeof(+mouse.style.left));
mouse.addEventListener('click', (event) => {
mouse.style.position = 'fixed';
mouse.style.left = mouse.getBoundingClientRect().left + 'px';
mouse.style.top = mouse.getBoundingClientRect().top + 'px';
})
mouse.addEventListener ('focus', (event) => {
mouse.addEventListener('keydown', (event) => {
if (event.keyCode == 37){
console.log('left');
let left = +mouse.style.left
mouse.style.left = left - 20 + 'px';
}
if (event.keyCode == 38){
console.log('up');
let up = +mouse.style.top;
mouse.style.top = up - 20 + 'px';
}
if (event.keyCode == 39){
console.log('right');
let right = +mouse.style.left
mouse.style.left = right + 20 + 'px';
}
if (event.keyCode == 40){
console.log('down');
let down = +mouse.style.top
mouse.style.top = down + 20 + 'px';
}
})
})
</script>

+ does not parse a string such as '20px' as 20. As mentioned in the comments, you need to parse your styles as a number. This means using a function such as parseInt as demonstrated below.
Also, registering an event handler inside an event handler may not result in what you wish. In particular: If you focus the div twice, the event handler will run twice.
var mouse = document.getElementById('mouse');
mouse.setAttribute('tabindex', '0')
mouse.addEventListener('click', (event) => {
mouse.style.position = 'fixed';
mouse.style.left = mouse.getBoundingClientRect().left + 'px';
mouse.style.top = mouse.getBoundingClientRect().top + 'px';
})
mouse.addEventListener ('focus', (event) => {
mouse.addEventListener('keydown', (event) => {
if (event.keyCode == 37){
console.log('left');
let left = parseInt(mouse.style.left)
mouse.style.left = left - 20 + 'px';
}
if (event.keyCode == 38){
console.log('up');
let up = parseInt(mouse.style.top);
mouse.style.top = up - 20 + 'px';
}
if (event.keyCode == 39){
console.log('right');
let right = parseInt(mouse.style.left)
mouse.style.left = right + 20 + 'px';
}
if (event.keyCode == 40){
console.log('down');
let down = parseInt(mouse.style.top)
mouse.style.top = down + 20 + 'px';
}
})
})
<div id="mouse" style="background-color: yellow">Hi</div>

Related

AngularJs Material textarea performance issue

Im using a form that contains a more than 40-50 textareas,
when the
md-no-autogrow option is enabled which it is by default,this causes a huge performance issue.
Function responsible
https://github.com/angular/material/blob/0b55529940d516a94777ca1d179e65df7835dd2a/src/components/input/input.js#L532
if I disable md-no-autogrow the resize functionalities are lost what could be a better solution?
Possible Solution
<textarea
ng-model="$ctrl.model"
ng-keydown="$ctrl.onKeyDown($event)"
ng-keyup="$ctrl.onKeyUp($event)"
md-no-autogrow="true"
>
onKeyUp(e) {
if (e.key === 'Enter') {
return;
}
let element = e.target;
element.style.height = 'auto';
if (element.scrollHeight > 54) {
element.style.height = element.scrollHeight + 'px';
}
}
onKeyDown(e) {
if (e.key !== 'Enter') {
return;
}
let element = e.target;
let numberOfLines = element.value.split('\n').length;
if (numberOfLines >= 2) {
element.style.height = 'auto';
element.style.height = (element.scrollHeight + 26) + 'px';
}
}

jQuery updating css state of class instances in a main.js file

I have a main.js file which I am initiating a game with two class instances. Head and Apple. I want to monitor css changes from my main.js file but it is not staying updated on the changes happening in the Head instance, namely, every 500 ms the position of it changes due to changes in its css. I would like to do certain actions depending on that "head's" positioning and therefore its css. Should I be using a jquery method to monitor this? I am not sure where to go. I have tried accessing the css properties by defining them with this in the constructor and also using variables in the main.js file. neither have worked.
main.js
$(document).ready(function() {
const head = new Head($('#board'));
const apple = new Apple($('#board'));
$('body').on('keydown', function(e) {
if (e.keyCode === 37) {
console.log('pressed left');
head.currentDirection = 'left';
} else if (e.keyCode === 39) {
console.log('pressed right');
head.currentDirection = 'right';
} else if (e.keyCode === 38) {
console.log('pressed up');
head.currentDirection = 'up';
} else if (e.keyCode === 40) {
console.log('pressed down');
head.currentDirection = 'down';
}
});
let position = head.node.position();
if (position.top === apple.randomTop && position.left === apple.randomLeft) {
this.endGame();
}
});
Apple
class Apple {
constructor($el) {
this.node = $('<img id="apple"></img>');
this.node.attr('src', 'src/assets/apple.jpg');
$el.append(this.node);
this.randomTop = Math.floor(Math.random() * 13) * 50
this.randomLeft = Math.floor(Math.random() * 13) * 50
this.node.css({ top: this.randomTop, left: this.randomLeft });
}
}
Head
// creates a constructor function - research ES6 classes
class Head {
// this is what's called when you use the "new" keyword
constructor($el) {
this.node = $('<div id="head"></div>');
this.currentDirection = 'right';
this.SPEED = 500;
$el.append(this.node);
this.node.css({ top: 0, left: 0 });
this.toBeCleared = setTimeout(this.move.bind(this), this.SPEED);
}
// same as Head.prototype.move = function() {...}
move() {
let direction = this.currentDirection;
let position = this.node.position();
if (position.left === 700 || position.top === 700 || position.left === -50 || position.top === -50) {
console.log('Game Over');
this.endGame();
}
if (direction === 'right') {
position.left += 50;
} else if (direction === 'left') {
position.left -= 50;
} else if (direction === 'up') {
position.top -= 50;
} else if (direction === 'down') {
position.top += 50;
}
this.node.css(position);
this.toBeCleared = setTimeout(this.move.bind(this), this.SPEED);
}
endGame() {
console.log('game has ended')
// this.node.css(position);
clearTimeout(toBeCleared);
}
}

In JavaScript I can use the style.left property to move a div around, but when I use style.right it doesn't work

I know you have to invert the properties and I've done that. I also replaced the style.right.replace function with style.left.replace and changed the other parts to move the left property ${left + 1} and it worked! This confirms there is no typo. style.right just doesn't work at all for me. Any thoughts on this code?
//This Works!
var dodger = document.getElementById('dodger')
function moveDodgerLeft() {
var leftNumbers = dodger.style.left.replace('px', " ")
var left = parseInt(leftNumbers, 10)
if (left > 0) {
dodger.style.left = `${left - 1}px`
}
}
document.addEventListener('keydown', function(e) {
if (e.which === 37) {
moveDodgerLeft()
}
})
// This doesn't work
function moveDodgerRight() {
var rightNumbers = dodger.style.right.replace('px', " ")
var right = parseInt(rightNumbers, 10)
if (right > 0) {
dodger.style.right =`${right - 1}px`
}
}
document.addEventListener('keydown', function(e) {
if (e.which === 39) {
moveDodgerRight()
}
})

Javascript function for moving div with arrow keys not working?

I've been trying to move a div around a page just using the arrows keys on my keyboard. It seems not to be working. I had it working before but for some reason it is no longer working. Could you let me know what you think the issue is? I have a feeling it has something to do with window.onkeydown and onkeyup.
Thank you for any help in advance.
CSS --
#log {
position:absolute;
width: 50px;
height: 50px;
border: 2px solid black;
background-color: white;
color: black;
font-size: 20px;
left: 20px;
}
HTML---
<div id="log"></div>
JavaScript --
var Keys = {
up: false,
down: false,
left: false,
right: false
};
var hero = {
x: 0,
y: 0
};
var log = document.getElementById("log");
window.onkeydown = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = true;
if(kc === 38) Keys.up = true;
if(kc === 39) Keys.right = true;
if(kc === 40) Keys.down = true;
};
window.onkeyup = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = false;
if(kc === 38) Keys.up = false;
if(kc === 39) Keys.right = false;
if(kc === 40) Keys.down = false;
};
function main() {
move();
};
function move(){
if(Keys.up){
hero.y -= 10;
var p = hero.y;
var t = p + 10;
log.style.top = p + "px";
log.style.bottom = t + "px";
//color();
}
if(Keys.down){
hero.y += 10;
var g = hero.y;
var q = g - 10;
log.style.bottom = g + "px";
log.style.top = q + "px";
//color();
}
if(Keys.left) {
hero.x -= 10;
var z = hero.x;
var q = z + 10;
log.style.left = z + "px";
log.style.right = q + "px";
//color();
}
if(Keys.right){
hero.x += 10;
var z = hero.x;
var q = z - 10;
log.style.right = z + "px";
log.style.left = q + "px";
// color();
}
}
setInterval(main, 50);
If you're open to using jQuery this might help you out.
$(document).ready(function() {
var hero = $("#log");
var speed = 1;
var direction = {
left: false,
up: false,
right: false,
down: false
};
$(document).on('keydown', function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) direction.left = true;
if (kc === 38) direction.up = true;
if (kc === 39) direction.right = true;
if (kc === 40) direction.down = true;
});
$(document).on('keyup', function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) direction.left = false;
if (kc === 38) direction.up = false;
if (kc === 39) direction.right = false;
if (kc === 40) direction.down = false;
});
function move() {
if (direction.left) hero.css("left", (hero.position().left - speed) + "px");
if (direction.up) hero.css("top", (hero.position().top - speed) + "px");
if (direction.right) hero.css("left", (hero.position().left + speed) + "px");
if (direction.down) hero.css("top", (hero.position().top + speed) + "px");
}
setInterval(move, 1);
});
Here's a Fiddle to demonstrate the result. Feel free to customize it to your needs.
UPDATE
And here's another Fiddle to accept multiple buttons pressed at the same time.

Unable to fetch the div style left value....

I have just started learning javascript and I was trying to move a div element using javascript. I was using the left and top property of style to move the div. The code is below.
html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
window.onload = function() {
divObj = document.getElementById('divObj');
window.onkeydown=function(e) {
var keycode;
keycode = e.keyCode;
speed = 1;
if(keycode == 37) {
divObj.style.left = (parseInt(divObj.style.left) - speed) + "px"; }
else if(keycode == 38)
divObj.style.top = (parseInt(divObj.style.top) - speed) + "px";
else if(keycode == 39)
divObj.style.left = (parseInt(divObj.style.left) + speed) + "px";
else if(keycode == 40)
divObj.style.top = (parseInt(divObj.style.top) + speed) - "px";
}
}
</script>
<style>
div.div1 { width : 200px;
height :50px;
background-color : #333;
position:absolute;
left:0px;
top:0px;
}
</style>
</head>
<body>
<div id = "divObj" class = "div1"></div>
</body>
</html>
The problem is that the 'divObj.style.left' is not returning any value and so the div cannot be moved using the up and down key.
If anyone knows how to get the values of style left property of the div, please let me know.
You need individual braces for all your else if statements
if(keycode == 37) {
divObj.style.left = (parseInt(divObj.style.left) - speed) + "px"; }
else if(keycode == 38){
divObj.style.top = (parseInt(divObj.style.top) - speed) + "px";}
else if(keycode == 39){
divObj.style.left = (parseInt(divObj.style.left) + speed) + "px"; }
else if(keycode == 40){
divObj.style.top = (parseInt(divObj.style.top) + speed) - "px";}
Try this
window.onload = function () {
divObj = document.getElementById('divObj');
window.onkeydown = function (e) {
var keycode;
keycode = e.keyCode;
speed = 1;
if (keycode == 37)
divObj.style.left =
((divObj.style.left == "" ? "0" : parseInt(divObj.style.left)) + speed) + "px";
else if (keycode == 38)
divObj.style.top =
((divObj.style.top == "" ? "0" : parseInt(divObj.style.top)) + speed) + "px";
else if (keycode == 39)
divObj.style.left = (
(divObj.style.left == "" ? "0" : parseInt(divObj.style.left)) + speed) + "px";
else if (keycode == 40)
divObj.style.top =
((divObj.style.top == "" ? "0" : parseInt(divObj.style.top)) + speed) + "px";
}
}
I made it this way
divObj = document.getElementById('divObj');
window.onkeydown=function(e) {
var keycode;
var lll = divObj.offsetLeft
var rrr = divObj.offsetTop
keycode = e.keyCode;
speed = 1;
if(keycode == 37) {
divObj.style.left = lll - speed+"px";}
else if(keycode == 38){
divObj.style.top = rrr - speed+"px";}
else if(keycode == 39){
divObj.style.left = lll + speed+"px";}
else if(keycode == 40){
divObj.style.top = rrr + speed+"px";}
}
jsfiddle

Categories

Resources