Moving an image from right to left by using style.left - javascript

I have moved the image left to right successfully. But when I tried to move image from right to left then also image moves towards right.actually the value of x in not decreasing.x=x-step doesn't decreases value of x. Help will be appreciated.
<script>
function disp(){
var step=1; // Change this step value
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
if(x <= 550 && y<=500 && y>=0 && x>=0)
{
x=x-step;
document.getElementById('i1').style.left= x + "px"; // horizontal movment
}
}
function timer(){
disp();
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
my_time=setTimeout('timer()',100);
}
</script>
<img src=image2.jpg id='i1' style="height:20px;width:20px;position:relative;left:300px;top:300px;">

Change your step to 10 and you will see it move left by 2px, set the step to 6 and you will see it move right by 2px. this is becuase there is a difference between the offsetleft and left by 8px, causing the funny behavior
You can subtract the diff like so: var x=document.getElementById('i1').offsetLeft - 8; (or calculate the difference), flip the x=x-step; to x=x+step; and it will move the opposite direction
<html>
<meta charset="utf-8" />
<img src='image2.jpg' id='i1' style="height:20px;width:20px;position:relative;left:300px;top:300px;" />
<script>
function disp(){
var step=1; // Change this step value
var y=document.getElementById('i1').offsetTop;
var x=x=document.getElementById('i1').offsetLeft - 8;
if(x <= 550 && y <=500 && y>=0 && x>=0)
{
x=x-step;
document.getElementById('i1').style.left = x + "px";
}
}
function timer(){
disp();
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
my_time=setTimeout('timer()',100);
}
timer();
</script>
</html>

Check out this fiddle please
function disp(){
var step;
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
if (x>1000){
clearTimeout(my_time);
}
if (x>=400){
dir = "left";
} else if (x<0){
dir = "right";
}
if(dir == "left")
{
step = -10;
} else {
step = 10;
}
x = x + step;
document.getElementById('i1').style.left= x + "px"; // horizontal movment
}
function tmr(){
disp();
my_time=setTimeout(function(){ tmr(); } ,100);
}
var my_time;
var dir = "right";
tmr();

Related

My JS animation resets its marginTop, but not its marginLeft

Im supernew to javascript animations. I just found out how to add the 2nd movement to my animation.
When running funk() function, the ball goes down to the right. When it triggers funktre() function, the ball goes to its starting marginTop position but keeps its marginLeft position.
Why does it return to the top? I want the 2nd animation, funktre(), to move the ball from the funk() ending position.
const ball = document.querySelector("#en");
ball.addEventListener("click", funk);
function funk() {
let id = null;
let position = 0;
clearInterval(id);
id = setInterval(funkto, 5);
function funkto() {
if (position == 450) {
clearInterval(id);
funktre();
// sett en ny funksjon her
}
else {
stop();
position++;
ball.style.marginLeft = position + "px";
ball.style.marginTop = position + "px";
}
}
};
function stop() {
ball.removeEventListener("click", funk);
};
function funktre() {
let idd = null;
let pos = 0;
clearInterval(idd);
idd = setInterval(funkfire, 5);
function funkfire() {
if (pos == 200) {
clearInterval(idd);
// ny funksjon her
}
else {
pos++;
ball.style.marginTop = pos + "px";
}
}
}
"I want the 2nd animation, funktre, to move the ball from the funk() ending position."
Then you should not initialize its starting position at zero, but at its current position.
function funktre() {
let idd = null;
let pos = parseInt(ball.style.marginTop); // set the initial pos to current pos
clearInterval(idd);
idd = setInterval(funkfire, 5);
function funkfire() {
if (pos == 200) {
clearInterval(idd);
// ny funksjon her
}
else {
pos++;
ball.style.marginTop = pos + "px";
}
}
}
If you intend to program more animations, or even a video game, I would suggest storing the ball top/left position in a global variable (which you could access from any scope).

Make a Javascript Animation continue without resetting

I am trying to get this function to be repeatable without resetting.
For example, when i press a button with this function, the button will move to the right from 0px to 100px. When I press the button again it will go from 100px to 200px and so on. It is supposed to animate as well, so it moves 1px at a time until the loop ends.
The code below only works as a one time use, as in it will move from 0px to 100px and pressing it again makes it go 0px to 100px.
I've been working on this for several hours and looked through many sources of help before asking.
function goRight() {
var pos = 0;
var count = pos;
var elem = document.getElementById("main");
var id = setInterval(move, 5);
function move() {
if(pos == count + 100){elem.style.left = pos + 'px'; clearInterval(id);}
else {pos++; elem.style.left = pos + 'px';}
}
}
function goRight() {
var elem = document.getElementById("main"); // the element
var origin = parseInt(elem.style.left) || 0; // get the left of the element (as an origin for the animation), 0 if not set yet
var pos = 0; // pos initialized to 0
var id = setInterval(move, 5);
function move() {
if(pos == 101) { clearInterval(id); } // if pos is 101, then stop the animation
else { pos++; elem.style.left = (origin + pos) + 'px';} // if not, then increment it and set the left of the element to pos + origin
}
}
I think you must only make pos as a global variable and initiate it outside goRight function
like this:
var pos = 0;
function goRight() {
var count = pos;
var elem = document.getElementById("main");
var id = setInterval(move, 5);
function move() {
if(pos == count + 100){elem.style.left = pos + 'px'; clearInterval(id);}
else {pos++; elem.style.left = pos + 'px';}
}
}
Whats wrong in your code is only every time you call goRight pos will be set to zero and again it will begin from start.
but with a global variable it will be save for next time interval will run.

How to use setInterval and clearInterval to move text diagonally left (back to start) after moving right and down

This is the result of what I am trying to accomplish using only JavaScript (no jQuery or CSS) with setInterval and clearInterval:
I have to begin moving the text from the top-left corner to the top-right corner of a window's browser. When it reaches the top-right corner, the text will begin to move down to the bottom-right corner. After that, it will go back to its start position and stop. I am able to move the text to the right and bottom, but not back to the start position. I have tried various ways to wrap my head around this one part and have been unsuccessful. Any help would be much appreciated. This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var thisLeft=0;
var thisTop=0;
var moveID=0;
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// Function to move the text
function moveText(){
var thisText= document.getElementById('myDiv');
if (thisLeft < width ){
thisLeft += 100; //how much the text moves right
}else if (thisLeft >= width) {
document.getElementById("myDiv").style.color = "blue";
document.getElementById("myDiv").style.fontSize= "xx-Large";
document.getElementById('myDiv').innerHTML= "moveDown";
thisTop +=100; //how much the text moves down
}
if (thisTop >= height && thisLeft >= width){
thisTop -= 100;
thisLeft -= 100;
}
thisText.style.left=thisLeft +"px";
thisText.style.top=thisTop +"px";
}
// how long it will take the text move to complete
function doMove(){
moveID=setInterval(moveText, 500);
}
</script>
</head>
<body onload= "doMove()" >
<div id="myDiv"style="position:absolute;" >
<p>movingRight</p>
</div>
</body>
</html>
I'd use a state based approach and move to another state after every change of direction.
One thing you'd also need to do, that I haven't included in my code below, is to scale either thisLeft or thisTop by the ratio of width to height to get back to the start due to the page not being square.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var thisLeft=0;
var thisTop=0;
var moveID=0;
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var state = 1;
// Function to move the text
function moveText(){
var thisText= document.getElementById('myDiv');
if (state == 1){
thisLeft += 100; //how much the text moves right
} else if (state == 2) {
thisTop +=100; //how much the text moves down
} else if (state == 3) {
thisTop -= 100;
thisLeft -= 100;
}
if (state == 1 && thisLeft >= width ){
state = 2;
document.getElementById("myDiv").style.color = "blue";
document.getElementById("myDiv").style.fontSize= "xx-Large";
document.getElementById('myDiv').innerHTML= "moveDown";
} else if (state == 2 && (thisTop >= height)) {
state = 3;
} else if (state == 3 && (thisLeft <= 0)) {
state = 0;
}
thisText.style.left=thisLeft +"px";
thisText.style.top=thisTop +"px";
}
// how long it will take the text move to complete
function doMove(){
moveID=setInterval(moveText, 500);
}
</script>
</head>
<body onload= "doMove()" >
<div id="myDiv"style="position:absolute;" >
<p>movingRight</p>
</div>
</body>
</html>
Example: http://jsbin.com/latotujuga/edit?html,output

JS - moving an image horizontally after a period of time

Everything was going smoothly until now. I want to have this hor() function reverse after 20 seconds. The original hor() function grabs an image offscreen and moves it horizontally from the left to the center of the page. I'd like to create a function that does the opposite after 20 seconds. The "after 20 seconds" part is giving me the most grief. If you could show me what a new function would look like or an 'else' addition to the current function that would be great. Thanks.
<script language="JavaScript" type="text/JavaScript">
var x = -500;
var y = 100;
function hor(val) {
if (x <= 500){
x = x + val;
document.getElementById("pos").style.left = x + "px";
setTimeout("hor(5)", 10);
}
}
</script>
<style type="text/css">
<!--
#pos {
position: absolute;
left: -500px;
top: 100px;
z-index: 0;
}
</style>
<body onLoad="setTimeout('hor(5)',5000)">
<div id="pos">
<img src="image.jpg">
</div>
Perhaps you could try changing the script to this:
// Define variables
var x = -500,
y = 100,
direction = 1;
// Function which moves "pos" element
function hor(val) {
// Move by specified value multiplied by direction
x += val * direction;
if(x > 500){
x = 500;
// Reverse direction
direction = -1;
} else if(x < -500){
x = -500;
// Reverse direction, once again
direction = 1;
}
// Move element
document.getElementById("pos").style.left = x + "px";
// Continue loop
setTimeout("hor("+val+")", 10);
}
This code will continue moving the pos element by the specified value until x greater than 500, at which point it will switch direction, then continue until x reaches -500, and so on.
EDIT:
This code will fix that issue with 20 seconds (I had thought that the 500 pixel thing computed to 20 seconds, lol).
// Define variables
var x = -500,
y = 100,
direction = 1;
firstCall = true;
timeElapsed = 0;
// Function which moves "pos" element
function hor(val) {
// Don't let the first call count!
if(!firstCall)timeElapsed += 10;
else firstCall = false;
if(timeElapsed >= 2000){
// Reverse direction
direction *= -1;
timeElapsed = 0;
}
// Move by specified value multiplied by direction
x += val * direction;
// Move element
document.getElementById("pos").style.left = x + "px";
// Continue loop
setTimeout("hor("+val+")", 10);
}
Try this. Here the img is moved horizontally and after sometime it is reverted back to its original position.
<script>
var x = -500;
var y = 100;
var op;
function hor(val) {
if (x <= 500 && x>=-500) {
x = x + val;
document.getElementById("pos").style.left = x + "px";
setTimeout(function(){hor(val);},10);
}
}
$(document).ready(function(){
setTimeout(function(){hor(5);},1000);
setInterval(function(){
setTimeout(function(){hor(-5);},1000);
},2000);
});
</script>
I have changed the timings for testing purpose only, you can change it back.

Javascript "ball" bouncing

I am a JS noob. I am getting into browser game programming and wanted to make a quick example of a ball dropping and bouncing just to learn. For some reason, when I created a jsfiddle my code actually didn't work, the onclick event for my div id="ball" didn't seem to be attaching, but when I run it in my browser it does. But that is not my question.
In this code, the user clicks the ball, which is just a div with a black bg. The div then follows the users cursor, and when the user clicks a second time, the div begins to fall towards the bottom of the window. When it hits the bottom, it should bounce back up, with an apex half the distance between the y coordinate of where it was originally dropped and the bottom of window. So if it was dropped at y position 600 and the bottom of the page is 800, the apex for the first bounce should be 700. The 2nd bounce, the apex would be 750. 3rd bounce, 775. You get the idea. Can someone help me a bit here? I am guessing I need to increment a counter each time the ball hits the bottom?
<html>
<head>
<style>
#ball {
width: 50px;
height: 50px;
background-color: black;
position: absolute;
}
</style>
<script>
window.onload = function() {
var ballClicked = false;
var ballFalling = false;
var ballX = 100;
var ballY = 100;
var timesBounced = 0;
var bounceApex = 0;
var startingDropHeight = 0;
var intervalVar;
var ball = document.getElementById("ball");
ball.style.left = ballX;
ball.style.top = ballY;
ball.onclick = function() {
if (ballClicked == false) {
ballClicked = true;
} else {
ballClicked = false;
ballFalling = true;
startingDropHeight = ballY;
intervalVar = setInterval(function(){dropBall()} , 5);
}
};
document.onmousemove = function(e) {
if (ballClicked == true) {
ballX = e.pageX;
ballY = e.pageY;
ball.style.left = ballX;
ball.style.top = ballY;
}
};
function dropBall() {
if (ballFalling == true) {
ballY = ballY + 1;
ball.style.top = ballY;
if (ballY == window.innerHeight - 50) {
timesBounced = timesBounced + 1;
bounceApex = (startingDropHeight + (window.innerHeight - 50)) / 2;
ballFalling = false;
if (bounceApex > window.innerHeight - 50) {
clearInterval(intervalVar);
}
};
} else {
ballY = ballY - 1;
ball.style.top = ballY;
if (ballY == bounceApex) {
ballFalling = true;
};
}
};
};
</script>
</head>
<body>
<div id="ball"></div>
</body>
</html>
When adding left and top styles, you need to specify the unit as well. So, instead of:
ball.style.left = 100;
it should be:
ball.style.left = "100px";
I've fixed that in your code and made a working jsfiddle, will improve the bouncing in a bit. See it here: http://jsfiddle.net/12grut99/
About the repetitive bouncing, this line is the issue:
bounceApex = (startingDropHeight + (window.innerHeight - 50)) / 2;
You're always calculating the apex based on the original drop height, yet after every bounce, the drop height should be the previous bounceApex (the highest point the ball reached).

Categories