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>
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'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>
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
I have this script that makes the header scroll up a bit when the user scroll the page and it is working fine. However, I want to make it scroll smoothly. I tried to do it myself, but I am not very good with java script.
<script>
window.onscroll=function () {
var top = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
if(top > 50){document.getElementById("header").style.position = "fixed";
document.getElementById("header").style.height="130px"
}
else {
document.getElementById("header").style.position = "relative";
document.getElementById("header").style.height="373px"
}
}
</script>
Here is an example: jsfiddle.net/largan/FDEJp
Any help is appreciated.
Thanks
I recommend you use position:fixed from the start. The browser is already doing a bunch of scrolling calculations for you so you definitely want to take advantage of that. The trick is to smoothly move the elements based on the position of the scroll. I'm using margin-top to position the content and height for the header. I have also cleaned up your markup to make better use of what the browser can already do. Notice I am moving the header and content separately, what his does is move the header in a more natural and intuitive way.
Markup
<div class="container">
<div id="header">
header
</div>
<div id="content">
<p>...</p>
</div>
</div>
CSS
.container {
width: 100%;
background-color: gray;
}
#header {
position: fixed;
text-align: center;
background: #880000;
height: 203px;
width: 100%;
top: 0;
left: 0;
}
#content {
margin-top: 203px;
margin-left: auto ;
margin-right: auto ;
}
JS
window.onscroll = function () {
var doc = document.documentElement,
body = document.body,
top = (doc && doc.scrollTop ||
body && body.scrollTop ||
0);
if(top < 75) {
document
.getElementById('header')
.style
.height = (203 - top * 2) + "px";
}
if(top < 130) {
document
.getElementById('content')
.style
.marginTop = (203 - top) + "px";
}
}
http://jsfiddle.net/FDEJp/2/
First of all, I would use a fixed positioning for both cases.
The next thing I would do, is use a 'switch' instead of an 'if':
switch (top)
{
case 0:
header.style.height="230px;
break;
case 1:
header.style.height="228px";
break;
case 2:
header.style.height="226px";
break;
case 3:
header.style.height="224px";
break;
case 4:
header.style.height="222px";
break;
case 5:
header.style.height="220px";
break;
case 6:
header.style.height="218px";
break;
case 7:
header.style.height="216px";
break;
case 8:
header.style.height="214px";
break;
case 9:
header.style.height="212px";
break;
case 10:
header.style.height="210px";
break;
case 11:
header.style.height="208px";
break;
case 12:
header.style.height="206px";
break;
case 13:
header.style.height="204px";
break;
case 14:
header.style.height="202px";
break;
case 15:
header.style.height="200px";
break;
case 16:
header.style.height="198px";
break;
case 17:
header.style.height="196px";
break;
case 18:
header.style.height="194px";
break;
case 19:
header.style.height="192px";
break;
case 20:
header.style.height="190px";
break;
default:
header.style.height="130px";
break;
}
You can see that to make it easier for me to write, I changed the ending height to 130 px, so that for every '1 top' you scroll, the header will be shorter in 2 pixels.
I don't have time so I didn't finish the code and didn't check it too, but when you write it and make your adjustments, you should have 49 cases, I only wrote 20.
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;
}
});