Adding a limit to moving a div with arrow keys - javascript

Hi I have added in functionality (found on stackoverflow) to make my div move left or right once the user holds down one of the arrow keys. All works as it should.
I want to know is there a way to stop the div from moving once it has reached the "end" or once it has moved a certain amount of pixels.
Code I have is below
$(document).keydown(function(e) {
switch (e.which) {
case 37:
$('#block').stop().animate({
left: '-=50'
}); //left arrow key
break;
case 39:
$('#block').stop().animate({
left: '+=50'
}); //right arrow key
break;
}
})

Sure, take a look at this fiddle: http://jsfiddle.net/ArtBIT/V7qcK/
var KEY = {
LEFT: 37,
RIGHT: 39
}
var boundaries = {
left: 0,
right: 200
}
$(document).keydown(function(e) {
var position = $('#block').position();
switch (e.which) {
case KEY.LEFT:
$('#block').stop().animate({
left: Math.max(boundaries.left, position.left - 50)
});
break;
case KEY.RIGHT:
$('#block').stop().animate({
left: Math.min(boundaries.right, position.left + 50)
});
break;
}
});​
Or this one http://jsfiddle.net/ArtBIT/8PWCR/1/ for 2D movement

Get the current offset and then handle it:
var max = 1000;
$(document).keydown(function(e) {
switch (e.which) {
case 37:
if($('#block').offset().left > 50)
{
$('#block').stop().animate({ left: '-=50' });
}
break;
case 39:
if($('#block').offset().left < (max - 50)
{
$('#block').stop().animate({ left: '+=50' });
}
break;
}
});

Related

Is there a way to call a function by a key press in Javascript?

Is there a way to call a function on the event of a key press.
My goal is to make a movable block and I was wondering if you could call the function to move a <div> block around. I also have an issue with making the character visible so it would be helpful to help me with that!
JavaScript
//variables
var player = document.getElementById('player');
var character = {
left: player.style.left + 1,
right: player.style.right + 1,
top: player.style.top + 1,
bottom: player.style.bottom + 1,
body: document.createElement('div'),
}
//functions
function running() {
console.log("Running");
console.log("Program running");
document.appendChild('div');
}
function loop() {
running();
}
function moveRight() {
character.style.position = absolute;
character.style.top = top + "px";
character.style.right = right + 2 + "px";
}
function moveLeft() {
character.style.position = absolute;
character.style.top = top + "px";
character.style.left = left + 2 + "px";
}
function moveup() {
character.style.position = absolute;
character.style.top = top + "px";
character.style.right = right + 2 + "px";
}
//functions called
loop();
HTML
<!DOCTYPE html>
<html>
<head>
<title>RPG</title>
</head>
<body>
<div id="allCode">
<script type="text/javascript" src="index.js"></script>
<style type="text/css" src="style.css"></style>
</div>
<div id="player"></div>
</body>
</html>
There are a lot of examples on how to deal with key handling events in javascript, this should get you started :
document.addEventListener('keydown', function(event) {
switch (event.keyCode) {
case 37:
//left function
break;
case 38:
//Up function
break;
case 39:
//Right function
break;
}
});
Edit: The .keyCode, .which, .charCode are deprecated properties:
so you should use event.key
for example:
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
switch (event.key) {
case "Up": // IE/Edge specific value
case "ArrowUp":
//Up function
break;
case "Left": // IE/Edge specific
case "ArrowLeft":
//left function
break;
case "Right": // IE/Edge specific
case "ArrowRight":
//Right function
break;
default:
return; // No key event
}
event.preventDefault(); // Avoid key handling twice
}, true);
Maybe this can lead you in the right direction. It's a link to move an object using arrow keys.
https://www.includehelp.com/code-snippets/move-object-with-arrow-keys-using-javascript-function.aspx

How do you make a moveable element, and bound it to screen size?

I'm making a simple web page with a cartoon image that the user can move around. I'd like to move the image with arrow keys, and then bound that movement to the available screen / window / document size with jQuery. In the code below, the constants at lines 1 - 4 aren't working, and I can't see why!
let width = Math.max($(document).width(), $(window).width());
let height = Math.max($(document).height(), $(window).height());
let height = $(window).height();
let width = $(window).width();
//Below is code which allows for the character to move:
$(document).keydown(function(key) {
document.write(Math.max($(document).height(), $(window)
.height()));
document.write(Math.max($(document).width(), $(window)
.width()));
switch (parseInt(key.which, 10)) {
// Left arrow key pressed
case 37:
if ($('img').position().left > 0) {
$('img').animate({
left: "-=20px"
}, 'fast');
}
break;
// Up Arrow Pressed
case 38:
$('img').animate({
top: '-=20px'
}, 'fast');
break;
// Right Arrow Pressed
case 39:
if ($('img').position().left < width) {
$('img').animate({
left: '+=20px'
}, 'fast');
}
break;
// Down Arrow Pressed
case 40:
$('img').animate({
top: '+=20px'
}, 'fast');
break;
}
});

Javascript moving div to new position with arrow keys

I want to make a div able to move with arrow keys in 4 direction with multikey support(e.x. moving to top left) onkeypress. When i click some of the arrows i expect moving to that direction until i put my finger up from that button. Although the move is just once which i don't understand why is happening.
function place(id,x_pos, y_pos) {
var element = document.getElementById(id);
element.style.position = "absolute";
element.style.left = x_pos+'px';
element.style.top = y_pos+'px';
}
setInterval(update,1);
function update(){
document.addEventListener('keydown', keyPress);
}
function keyPress(e) {
var x = e.keyCode;
switch (x) {
case 37:
place('move', move.style.left-10, move.style.top);
break;
case 39:
place('move', move.style.left+10, move.style.top);
break;
case 38:
place('move', move.style.left, move.style.top-10);
break;
case 40:
place('move', move.style.left, move.style.top+10);
break;
}
// console.log(x);
}
*{
margin:0;
padding:0;
}
div#move{
background-color:yellow;
width:5vw;
height:5vw;
}
<div id='move'></div>
The problem with your code is that element.style.left give result as 10px and when you add 10 on 10px it will be a string like 10px10 which will make the property value incorrect.Since the first time the property is not set so first assignment id working fine. You need to get the left and right in numerical.
You also do not need to bind the update function with document with setInterval. Once is enough.
Check the code below
function place(id,x_pos, y_pos) {
var element = document.getElementById(id);
element.style.position = "absolute";
element.style.left = x_pos+'px';
element.style.top = y_pos+'px';
}
function update(){
document.addEventListener('keydown', keyPress);
}
function keyPress(e) {
var x = e.keyCode;
var move = document.getElementById("move").getBoundingClientRect();
var left = parseInt(move.left,10);
var top = parseInt(move.top,10)
switch (x) {
case 37:
place('move', left -10, top);
break;
case 39:
place('move', left+10, top);
break;
case 38:
place('move', left, top-10);
break;
case 40:
place('move', left, top+10);
break;
}
// console.log(x);
}
update();
*{
margin:0;
padding:0;
}
div#move{
background-color:yellow;
width:5vw;
height:5vw;
}
<div id='move'></div>
const move=document.getElementById('move');
var moveLeft = 0;
function direction(e){
if(e.keyCode==39){
moveLeft +=2;
move.style.left = moveLeft + 'px';
if(moveLeft>=600){
moveLeft -=2;
}
}
if(e.keyCode==37){
moveLeft -=2;
move.style.left = moveLeft + 'px';
}
if(e.keyCode==38){
moveLeft -=2;
move.style.top = moveLeft + 'px';
if(moveLeft>=600){
moveLeft +=2;
}
}
if(e.keyCode==40){
moveLeft +=2;
move.style.top = moveLeft + 'px';
}
}
document.onkeydown = direction;
#move{
position: absolute;
height: 50px;
width: 50px;
background-color: yellow
}
<div id="move"></div>
You don't need setInterval. Just register your listener, and it will handle every keypress.
document.addEventListener('keydown', keyPress);
function keyPress(e) {
var x = e.keyCode;
switch (x) {
case 37:
place('move', move.style.left-10, move.style.top);
break;
case 39:
place('move', move.style.left+10, move.style.top);
break;
case 38:
place('move', move.style.left, move.style.top-10);
break;
case 40:
place('move', move.style.left, move.style.top+10);
break;
}
// console.log(x);
}

Make border block for element in html

This is my code to make spaceship move using arrow-key and I need to block moving this elements(spaceship) from out the page range?
I mean when press down key the element make go to down I don't need that please this is my code:
$(document).keydown(function(e){
$("body").innerWidth()
switch (e.which){
case 37: //left arrow key
$(".box").finish().animate({
left: "-=50"
});
break;
case 38: //up arrow key
$(".box").finish().animate({
top: "-=50"
});
break;
case 39: //right arrow key
$(".box").finish().animate({
left: "+=50"
});
break;
case 40: //bottom arrow key
$(".box").finish().animate({
top: "+=50"
});
break;
}
css :
.box{
position: relative;
top: 10px;
width: 130px;
height: 130px;
position: relative;
margin: 200px auto 0;
background: url("http://davidpapp.com/wp-content/uploads/2015/05/rocket.png") ;
}
Take a moment to review the logic of your script. When the button is pressed, it just moves the objects regardless of its location on the page. Instead, you should include a conditional to check whether it can/should move before performing the actual move.
$(document).keydown(function(e){
var width = $("body").innerWidth();//Assigned this value to a variable
var height = $('body').height();//Created a variable for the height
var $box = $('.box');//Because I hate typing this so many times
var posX = parseFloat($box.css('left'));
var posY = parseFloat($box.css('top'));
switch (e.which) {
case 37: //left arrow key
//Don't allow if moving to the left would cause it to go less than 0
if(posX - 50 >= 0) {
$box.finish().animate({
left: "-=50"
});
}
break;
case 38: //up arrow key
//Don't allow if moving up would cause it to go less than 0
if(posY - 50 >= 0) {
$box.finish().animate({
top: "-=50"
});
}
break;
case 39: //right arrow key
//Not only checking to make sure the origin doesn't go over the width
//but also keep the width of the box in mind so it appears to stay within bounds
if(posX + 50 + $box.width() <= width) {
$box.finish().animate({
left: "+=50"
});
}
break;
case 40: //bottom arrow key
//Not only checking to make sure the origin doesn't go past the bottom line
//but also keep the height of the box in mind so it appears to stay within bounds
if(posY + 50 + $box.height() <= height) {
$box.finish().animate({
top: "+=50"
});
}
break;
}
}
P.S. I wrote this pretty quickly and without testing, so don't be surprised if I made a spelling error or have a less than sign and greater than sign mixed up, haha. I hope you understand the logic I'm trying to convey, anyway.
Below code to show what to do. You can tweak the numbers though
$(document).keydown(function(e){
$("body").innerWidth()
var width = window.innerWidth;
var height = window.innerHeight;
var offset = $(".box").offset();
switch (e.which){
case 37:
if(offset.left>=50)
$(".box").finish().animate({
left: "-=50"
});
break;
case 38:
if(offset.top>=100)
$(".box").finish().animate({
top: "-=50"
});
break;
case 39: //right arrow key
if(offset.left+130+50 < width)
$(".box").finish().animate({
left: "+=50"
});
break;
case 40: //bottom arrow key
if(offset.top+50 < height)
$(".box").finish().animate({
top: "+=50"
});
break;
}
})
body{
}
.box{
position: relative;
top: 10px;
width: 130px;
height: 130px;
position: relative;
margin: 200px auto 0;
background: url("http://davidpapp.com/wp-content/uploads/2015/05/rocket.png") ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="box"></div>

Continously move div with arrow keys

I found a fiddle that moves a div when pressing the arrow keys on your keyboard, however it needs to be pressed each time to get a fluid movement.
So how do you move a div like the example below, but by keeping the arrow key pushed down?
http://jsfiddle.net/ambiguous/N5Ltt/2/
jQuery
$(document).keydown(function(e) {
switch (e.which) {
case 37:
$('div').stop().animate({
left: '-=50'
}); //left arrow key
break;
case 38:
$('div').stop().animate({
top: '-=50'
}); //up arrow key
break;
case 39:
$('div').stop().animate({
left: '+=50'
}); //right arrow key
break;
case 40:
$('div').stop().animate({
top: '+=50'
}); //bottom arrow key
break;
}
});
HTML
div{
background:#ccc;
height:100px;
width:100px;
position: absolute;
top: 0;
left: 0;
}
This could be an approach for you:
var pressed = false;
$(document).keydown(function(e) {
if(!pressed){ //only start animation once
width = $(this).width();
height = $(this).height();
switch (e.which) {
case 37:
$('div').stop().animate({
left: '-=' + width //allow the user the move the div over the whole doc
}, 2000); //left arrow key
break;
// and so on
}
}
pressed = true;
}).keyup(function(){
$('div').stop(); // stop the current animation
pressed = false;
});
perhaps you have to change the variables width and height to fit in your needs.
DEMO
you could set a variable to true when the key is pressed down and false when the key is let go

Categories