Non-Linear DOM Animations - javascript

Question: WHAT THE "myMove()" METHOD DOES? Can you explain it?
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
Click Me
function myMove() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}

Quick note: In this answer, I'll be assuming the final question reads:
What does the `myMove()` method do?
Let's first take a look at the variables:
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
The variable elem refers to the red box which is being moved across the canvas (a div element). We set the pos tick variable to 0, which will control how many times we will move the box across the screen. Finally, id refers to a setInterval function which calls the defined frame function every 10 milliseconds.
Now let's look at the function frame:
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
First, it runs a quick check to see if the ticks are done, or in other words, checks to see if the position is 350. Then, if it is, it stops the loop. If it is not, it makes the box move down 1 pixel by setting the position from the top to the pos variable.
All of this code is contained within the myMove() function.

Related

jQuery make image popup in random position not working

I want to make an image randomly show up every 2 sec using jQuery. But the image always shows in a static position (top-left). I console.logged the attribute of the image and its left and top shows random px.
let score = 0;
let id = 0;
$(document).ready(function () {
setInterval(setImage, 2000);
});
function setImage() {
$("#container").append(
`<img src='images/virus.gif' id='${id}' width='75px' position='absolute' class='virus' left=${randomLeft()} top=${randomTop()}/>`
);
$("#" + id)
.slideUp(0)
.fadeIn(1000);
id++;
$("#" + id).on("click", function (event) {
$(event.target).remove();
score++;
console.log($(event.target).attr("id"), score);
});
}
function randomTop() {
let height = $(window).height();
let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
return randomHeight;
}
function randomLeft() {
let width = $(window).width();
let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
return randomLeft;
}
You need to use style rather than left/top attributes
style="left:10px;right:10px"
Couple of other tweaks to your snippet:
include jquery (option on the left of snippet editor adds <script> to the html)
needs a #container to put them in, I made this position:relative so the position:absolute will work
removed the need for the $("#"+id) re-finding by chaining the append
put the i++ at the beginning so that you don't try to attach click to something that doesn't exist yet (but doesn't matter as not used for re-finding new element)
$(this).remove() must come after $(this).attr("id") - you were removing it before getting its ID
used this inside the click handler rather than event.target
would be better as data-id=${++id} rather than using a numerical id, but that's a small change (not made)
Updated snippet:
let score = 0;
let id = 0;
$(document).ready(function() {
setInterval(setImage, 2000);
});
function setImage() {
var img = $(`<img src='images/img4.jpg' id='${++id}' class='virus' style='left:${randomLeft()};top:${randomTop()}' />`);
img.appendTo("#container")
.slideUp(0)
.fadeIn(1000)
.on("click", function() {
score++;
console.log($(this).attr("id"), score);
$(this).remove();
});
}
function randomTop() {
let height = $(window).height();
let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
return randomHeight;
}
function randomLeft() {
let width = $(window).width();
let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
return randomLeft;
}
#container {
position: relative;
height: 100%;
width: 100%;
}
.virus {
border: 1px solid red;
position: absolute;
width: 75px;
height: 20px;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>

animation using javascript - how to move an object upwards

Following is my code, there is a small box inside a container box, on click of button, it animates to down and hits the bottom of the container, and then it should rise up from there. But instead it starts flickering rapidly at the same place. Pls tell me how to rise the box once it hits the bottom .
<style>
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<p>
<button id=button>Click Me</button>
</p>
<div id ="myContainer">
<div id ="myAnimation">Fish</div>
</div>
<script>
button =document.getElementById("button");
button.onclick = function() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
/*if (pos == 350) {
clearInterval(id);
}
else*/
if(pos<175)
{
pos++;
elem.style.top = 2*pos + 'px';
elem.style.left = pos + 'px';
}
else
{
pos--;
elem.style.top = pos + 'px';
elem.style.right = pos + 'px';
}
}
}
</script>
Hi made a little solution, you need a switch to made up untill go top, and reveerse to bottom.
button =document.getElementById("button");
button.onclick = function() {
var elem = document.getElementById("myAnimation");
var pos = 0, up=false;
var id = setInterval(frame, 10);
function frame() {
console.log(up, pos);
/*if (pos == 350) {
clearInterval(id);
}
else*/
if(pos<175 && !up)
{
pos++;
if(pos===175) up=true;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
else
{
pos--;
if(pos<=0) up=false;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}

how to hide an element at the end of javascript animation

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);
}
}

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';
}
}

Categories