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
Related
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;
}
});
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);
}
I'm trying to make a simple image move on the screen with the arrow keys up, down, left and right. It works fine except that the image keeps going out of the window and I can't see. What I want to do is keep the image within the window bounds and not go out of it.
Here's my code:
let height = $(window).height();
let width = $(window).width();
$(document).keydown(function(key) {
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:
if ($('img').position().top > 0) {
$('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:
if ($('img').position().top < height) {
$('img').animate({
top: '+=20px'
}, 'fast');
}
break;
}
});
body {
width: 100%;
height: 100%;
background: blue;
overflow: hidden;
/*This is the solution*/
}
img {
position: relative;
left: 0;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img src="http://pngimg.com/uploads/mario/mario_PNG129.png" />
Seems like you just need to account for one more calculation. Using the right movement as an example, what happens if the current right position of the image is 5px from the edge of the screen? Then ($('img').position().right > width) would compute to true and it would move 20px, putting it 15px off the screen.
So, you simply need to account for this potential.
if($('img').position().right > 0){
distance = ( ($('img').position().left - width) < 20 ) ? ($('img').position().left - width) : 20;
$('img').animate({left: "+="+distance+"px"}, 'fast');
}
Here we are saying, if the current position of the image is less than 20px from the right edge, only move it that difference, otherwise, move it 20px.
Similar logic would need to be applied to the bottom to ensure the image does not move more than the height of the screen.
I would recommend applying the same logic to the bottom and left as well. The reason it doesn't move off the screen currently is because you are starting from 0,0 and move 20px at a time. It will always come back to 0,0. However, if you have to move it to the right 12px to stay within bounds, then when you move it back, you could run into the same issue on the left. Hope that makes sense.
i hope my code will bring you some clues
$(document).ready(function(){
//alert("This page has loaded!");
//Below is code which hides a paragraph when the button is clicked
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
//let width=Math.max($(document).width(), $(window).width());
//let height=Math.max($(document).height(), $(window).height());
let height=$(window).height();
let width=$(window).width();
var w =document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
//Below is code which allows for the character to move - why not try craft your own
//version?
$(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>1 ){
$('img').animate({left: "-=70px"}, 'fast');}
break;
// Up Arrow Pressed
case 38:
if($('img').position().top >1 ){
$('img').animate({top: '-=20px'},'fast');}
break;
// Right Arrow Pressed
case 39:
if($('img').position().left<(w-185) ){
$('img').animate({left: '+=70px'},'fast');}
break;
// Down Arrow Pressed
case 40:
if($('img').position().top<(h-185) ){
$('img').animate({top: '+=70px'},'fast');}
break;
}
});
});
img {
position: relative;
left: 0;
top: 0;
right: 0;
}
body{
width: 100%;
height: 100%;
background: cyan;
overflow: auto;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='stylesheet.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!--Including jQuery -->
<script type='text/javascript' src="script.js"></script> <!-- Including the scripting file -->
</head>
<body>
<img
src="http://staublicht.net/wordpress/wp-content/uploads/2011/08/walk_animation.gif"/>
</body>
</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>
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;
}
});