How to prevent image from going out of the window with JQuery - javascript

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>

Related

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>

Stop specific transition before occuring

I've got quite a rudementary question that I can't really seem to fix myself. I've already looked into similar answers, but none of the implementations seem to be possible implementations for me.
Basically I have an image(png) that moves around in a little box (here is the game).
The problem I'm facing is that the image should flip if you change the direction the sprite is moving (left-right) and that it should be able to jump.
The transitions work fine separately, but when I try to jump when faced left it turns right in the jump.
I need to remove the baddie-left before jumping, I suppose. But it doesn't seem to work when I've done it...
Full disclaimer: We are not supposed to use anything but 'normal' js (ie. no jquery).
Here is the js:
switch(key) {
case 32: //jumping
if(!baddie.classList.contains('baddie-jumping')){
baddie.classList.add('baddie-jumping');
window.setTimeout(function(){
baddie.classList.remove('baddie-jumping');
}, 350);
}
break;
case 37: //moving left
if (left_available(left - step)){
if(!baddie.classList.contains('baddie-left')){
baddie.classList.add('baddie-left');
}
left = left - step;
} else {
left = 150;
top = 130;
}
break;
case 38:
if (top_available(top - step)){
top = top - step;
} else {
left = 150;
top = 130;
}
break;
case 39: //moving right
if (left_available(left + step)){
if(baddie.classList.contains('baddie-left')){
baddie.classList.remove('baddie-left');
}
left = left + step;
} else {
left = 150;
top = 130;
}
break;
case 40:
if (top_available(top + step)){
top = top + step;
} else {
left = 150;
top = 130;
}
break;
}
And the css:
.content {
/* If #content position is absolute, the #baddie position will be given in reference to it's parent, which is #content
* Makes it easier to do collision calculations */
position: absolute;
width: 400px;
height: 300px;
border: solid 1px #000;
}
.baddie{
/* Baddie's postition must be absolute, otherwise we can't move him by changing top and left */
position: absolute;
height: 50px;
width: 50px;
/* Change this to your own baddie! */
background: url("../img/viking.png");
background-size: 50px;
transition: all 0.35s ease;
}
.baddie-left {
transform: rotateY(180deg);
}
.baddie-jumping {
transform: scale(1.5) translateY(-40px);
}
When you add .baddie-jumping class, it just overwrite transform property of .baddie-left class. You should add to your css:
.baddie-left.baddie-jumping {
transform: scale(1.5) translateY(-40px) rotateY(180deg);
}

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

div cannot animate bottom side and goes outside from window screen from every side

this is working fine with left,right and top animate div move from left side, right side and top side but it is not working with bottom side div can not move bottom. and also when i press key more than ten time or more quikly it goes outside from my window screen from every side and if i press key after one animation finish it can not goes out side.
my html code:
<body>
<div class="block"></div>
</body>
my css code:
div {
position: absolute;
background-color: #abc;
left: 50px;
top:50px;
width: 100px;
height: 100px;
}
my jquery code:
$(window).load(function(e) {
$("body").keydown(function(e) {
var width1 = $(window).width();
var heigth1 = $(window).height();
if(e.keyCode == 37) { // left
if (parseInt($('.block').css('left')) >= 50) {
$('.block').animate({left: '-=50'},"slow");
}
}
else if(e.keyCode == 39) { // right
if (parseInt($('.block').css('left')) <= (width1 - 150)){
$(".block").animate({left: "+=50px"},'slow');
}
}
else if(e.keyCode == 40){ // bottom
if (parseInt($('.block').css('top')) <= (height1 - 150)) {
$(".block").animate({'top':'+=50px'},'slow');
}
}
else if(e.keyCode == 38){ // top
if (parseInt($('.block').css('top')) >= 50) {
$(".block").animate({'top':'-=50px'},'slow');
}
}
});
});
there is my example, hope i help you :)
example
:)
Typo!
var heigth1 = $(window).height();
should be
var height1 = $(window).height();

stop animate outside of my window screen

this is working fine with left animate div cannot goes outside from left side but it is not working with right side div goes outside of window screen.
my html code:
<body>
<div class="block"></div>
</body>
my css code:
div {
position: absolute;
background-color: #abc;
left: 50px;
top:50px;
width: 90px;
height: 90px;
margin: 5px;
}
my jquery code
$("body").keydown(function(e) {
var width = $(window).width();
var heigth = $(window).height();
if(e.keyCode == 37) { // left
if (parseInt($('.block').css('left')) >= 50) {
$('.block').animate({left: '-=50'},"slow");
}
}
else if(e.keyCode == 39) { // right
if (parseInt($('.block').css('left')) <= width) {
$(".block").animate({left: "+=50px"},'slow');
}
}
});
thanks in advance.
When comparing the current left value to window width, you're not adding the 50px that will be added as the result of the function, thus you will go outside the width of the window.
You should also account for the width of the .block element itself
//...
else if(e.keyCode == 39) { // right
if ((parseInt($('.block').css('left')) + 50 + $('.block').width()) <= width) {
$(".block").animate({left: "+=50px"},'slow');
}
}
//...
Improve some code to #lukiffer's answer.
//...
else if(e.keyCode == 39) { // right
if (parseInt($('.block').css('left')) <= (width-150) ) {
$(".block").animate({left: "+=50px"},'slow');
}
}
//...

Categories