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
Related
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>
I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}
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.
I want call below code from HTML on event (right arrow key).
var Anim = function() {
var box = document.getElementById("square");
};
Anim.prototype.Start = function(event){
if(event.keyCode == 39){
box.style.left = (box.offsetLeft + 100)+"px";
}
};
Anim.prototype.Stop = function(event){
if(event.keyCode == 37){
box.style.left = (box.offsetLeft)+"px";
}
};
var Myanim = new Anim();
Here is my HTML
<div id="square" style="position: absolute;">This is my box</div>
Using jQuery :
$(document).keypress(function(event) {
alert('Handler for .keypress() called. - ' + event.charCode);
});
To import jquery in your project :
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
If you want to use Javascript only :
window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 37) { //left key
alert('up');
} else if (code === 40) { //down key
alert('down');
}};
I have a searchable textbox which populates a div with the search results. The div is scrollable. What I am trying to achieve, is to navigate through the result items with page up and down (keycode 38 & 40). But as soon as I try this, the whole div scrolls, and the result item itself does not take on the new selected css class.
Below is some of my code
this.TagNavigation = function (event) {
var div = $("#TagSearchResults");
var anchors = $("#TagSearchResults a");
var selectedAnchor = $("#TagSearchResults a.selected");
var position = anchors.index(selectedAnchor);
if (event.keyCode == "13" && anchors.length > 0) {
FRAMEWORK.AddUpdateInterventionTags(selectedAnchor.attr("id").split("-")[1] + "|" + selectedAnchor.text(), "add");
}
if (event.keyCode == "13" && anchors.length == 0 && $("#txtTagSearch").val() != "Start typing to search Tags") {
FRAMEWORK.AddNewTag($("#txtTagSearch").val());
}
else if (event.keyCode == "38") {
if (position > 0) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position - 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
}
}
else if (event.keyCode == "40") {
if (position <= anchors.length) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position + 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
//newSelectedAnchor.focus();
}
}
};
this.AjaxSearch = function (text) {
var div = $("#TagSearchResults");
var anchors = $("#TagSearchResults a");
var selectedAnchor = $("#TagSearchResults a.selected");
var position = anchors.index(selectedAnchor);
if (event.keyCode == "13") {
FRAMEWORK.TagNavigation(event);
}
else if (event.keyCode == "38") {
FRAMEWORK.TagNavigation(event);
}
else if (event.keyCode == "40") {
FRAMEWORK.TagNavigation(event);
}
else if (text.length >= 3) {
FRAMEWORK.RenderSearchResults(text);
}
else {
$("#TagSearchResults").html("");
$("#TagSearchResults").hide();
}
};
As you can see in the TagNavigation function (keycode 40), I tried to set the focus on the active element, but still no success.
Any help please.
You need to check weather the newly selected element has a higher Y value that the bottom of the containing div. If so, then scroll the div by the height of the new element. Change your 'if (event.keyCode == "40")' statement to the following:
this.TagNavigation = function (event) {
var div = $("#TagSearchResults");
var anchors = $("#TagSearchResults a");
var selectedAnchor = $("#TagSearchResults a.selected");
var position = anchors.index(selectedAnchor);
if (event.keyCode == "13" && anchors.length > 0) {
FRAMEWORK.AddUpdateInterventionTags(selectedAnchor.attr("id").split("-")[1] + "|" + selectedAnchor.text(), "add");
}
if (event.keyCode == "13" && anchors.length == 0 && $("#txtTagSearch").val() != "Start typing to search Tags") {
FRAMEWORK.AddNewTag($("#txtTagSearch").val());
}
else if (event.keyCode == "38") {
if (position > 0) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position - 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
var newSelectedAnchorPosistion = newSelectedAnchor.offset();
var divPosition = div.offset();
divPosition = divPosition.top;
if (newSelectedAnchorPosistion.top + 1 > divPosition) {
var newPos = div.scrollTop() - newSelectedAnchor.outerHeight();
div.scrollTop(newPos);
}
}
}
else if (event.keyCode == "40") {
if (position < anchors.length - 1) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position + 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
var newSelectedAnchorPosistion = newSelectedAnchor.offset();
var divPosition = div.offset();
divPosition = divPosition.top + div.outerHeight();
if (newSelectedAnchorPosistion.top + 1 >= divPosition) {
var newPos = div.scrollTop() + newSelectedAnchor.outerHeight();
div.scrollTop(newPos);
}
}
}
};