how to hide an element at the end of javascript animation - javascript

I know similar questions have been asked before, but the answers did not help me because they are too advanced for me and my simple animation. I am at the very beginning of javascript. On my website, I have the simple code for moving an element from one posotion to another. I would like to have it disappear when it reaches the final position, not fading out, just suddenly disappear. Should I do it with opacity change? How do I write it? My code is the following.
function myMove() {
var elem = document.getElementById("animation");
var pos = 100 ;
var id = setInterval(frame, 5);
function frame() {
if (pos == 380) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}

To hide an element simply set style.display to 'none'.
For example:
function myMove() {
var elem = document.getElementById("animation");
var pos = 100 ;
var id = setInterval(frame, 5);
function frame() {
if (pos == 380) {
clearInterval(id);
// this is the key line
elem.style.display = 'none';
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
Just as a heads up, using chained setTimeouts can be better than using setInterval in HTML animation. The reason being that if the animation (and/or other scripts on the page) takes longer than the interval the browser will become unresponsive. With a chain of setTimeouts, the clock doesn't start ticking until the end of the current frame.
For example, you could do:
function myMove() {
var elem = document.getElementById("animation");
var pos = 100 ;
function frame() {
if (pos == 380) {
// this is the key line
elem.style.display = 'none';
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
// set a timeout for 5 ms
setTimeout(myMove, 5);
}
}

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).

Trying to make progress bar move incrementally

How can I make my progress bar show in increments based on my question number. Currently it completes to 100% after clicking the next question button. But, I am trying to let it increase in the increments of the question numbers and go backwards if the previous question button is clicked. The codepen with all the code is here. Thank you.
var i = 0;
function moveForward() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
function moveBackward() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
///// UPDATED FUNCTION
function moveForward(i) {
console.log('i: ' + i);
var elem = document.getElementById("myBar");
switch(i) {
case 0:
elem.style.width = "33%";
elem.innerHTML = "33%";
break;
case 1:
elem.style.width = "66%";
elem.innerHTML = "66%";
break;
case 2:
elem.style.width = "100%";
elem.innerHTMl = "100%";
}
}
The reason it is completing after one click is that setInterval runs the function repetitively every x milliseconds. That means that your frame function runs every 10 milliseconds until it hits the if statement that clears the interval. Since your stop check only stops at width >= 100 it continues to expand until it is set to 100%.
In order to properly track the existing and next widths you will need to have a persistent variable in a global scope and you'll need to pass a target width to frame so that it knows when to actually stop
There are two other issues with your code. The first is that the previous button also increases the width rather than decreasing it, and the other issue is that every time you click the next or previous buttons it first resets the width to 10 and then increases it to 100.

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.

Looping an animation in javascript continuously

My question is how to loop an animation continuously. For example please follow the link below of W3School where a simple box moves from top to bottom and then stops.
http://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3
But what I can't figure out is how to make this box animation non stop i.e. after it goes to the bottom it again moves up to its starting place and the animation continues forever.
You can make these adjustments to the JS:
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 150) { pos = 0; }
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
#container { width: 200px; height: 200px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background-color: red; }
<div id ="container">
<div id ="animate"></div>
</div>
Delete the clearInterval(id); that stops the animation timer and in its place add this pos = 0; to reposition the box every time it reaches the corner.
Change script to this and it won't stop anymore. runAlready is needed to lock appearing of the second rectangle and pos=0 in the if statement set the coordinate of the rectangle to the top left corner.
var runAlready=false;
function myMove() {
if(!runAlready){
runAlready=true;
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
pos=0;
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
}
The setInterval(frame, 5) tells the program to call the frame() function every 5/1000th of a second. That is what creates the animation.
The clearInterval(id) function tells it to stop the animation.
Take a look at the change I added below. It uses a variable named 'direction' to change the direction of the box. Rather than stopping the animation when the box gets to the LR corner, it reverses the direction and keeps going.
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
var direction = 1;
function frame() {
if (pos == 0){
direction = 1;
} else if(pos == 350){
direction = -1;
}
pos += direction;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}

javascript toggle animation issue

I am doing a small javascript animation. this is my code :
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
heading.onclick = function () {
var divHeight = 250;
var speed = 10;
var myInterval = 0;
alert(divHeight);
slide();
function slide() {
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
alert('i am called as slide down')
}
}
function slideUp() {
var anima = document.getElementById('anima');
if (divHeight <= 0) {
divHeight = 0;
anima.style.height = '0px';
clearInterval(myInterval);
} else {
divHeight -= speed;
if (divHeight < 0) divHeight = 0;
anima.style.height = divHeight + 'px';
}
}
function slideDwn() {
var anima = document.getElementById('anima');
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
} else {
divHeight += speed;
anima.style.height = divHeight + 'px';
}
}
}
}
i am using above code for simple animation. i need to get the result 250 on the first click, as well second click i has to get 0 value. but it showing the 250 with unchanged. but i am assigning the value to set '0', once the div height reached to '0'.
what is the issue with my code? any one help me?
Everytime you click on the div the divHeight variable is reset to 250, thus your code never calls slideDwn. Moving the divHeight declaration outside the event handler should do the trick.
Also, your div wont have the correct size when any of the 2 animations end. You're setting the divHeight variable to 250 or 0 correctly, but never actually setting anima.style.height after that.
I've rewritten your code into something simpler and lighter. The main difference here is that we're using a single slide() function here, and that the height of the div in question is stored in a variable beforehand to ensure that the element slides into the correct position.
Note that this is a very simplistic implementation and assumes that the div carries no padding. (The code uses ele.clientHeight and ele.style.height interchangeably, which admittedly, is a pretty bad choice, but is done here to keep the code simple)
var heading = document.getElementsByTagName('h1')[0],
anima = document.getElementById('anima'),
divHeight = anima.clientHeight,
speed = 10,
myInterval = 0,
animating = false;
function slide(speed, goal) {
if(Math.abs(anima.clientHeight - goal) <= speed){
anima.style.height = goal + 'px';
animating = false;
clearInterval(myInterval);
} else if(anima.clientHeight - goal > 0){
anima.style.height = (anima.clientHeight - speed) + 'px';
} else {
anima.style.height = (anima.clientHeight + speed) + 'px';
}
}
heading.onclick = function() {
if(!animating) {
animating = true;
var goal = (anima.clientHeight >= divHeight) ? 0 : divHeight;
myInterval = setInterval(slide, 13, speed, goal);
}
}
See http://www.jsfiddle.net/yijiang/dWJgG/2/ for a simple demo.
I've corrected your code a bit (See working demo)
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
var anima = document.getElementById('anima');
var divHeight = 250;
heading.onclick = function () {
var speed = 10;
var myInterval = 0;
function slideUp() {
divHeight -= speed;
if (divHeight <= 0) {
divHeight = 0;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slideDwn() {
divHeight += speed;
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slide() {
console.log(divHeight )
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
}
}
slide();
}
}​

Categories