I'm trying to learn Java Script Animations and I found really good examples on this site: http://javascript.info/tutorial/animation#maths-the-function-of-progress-delta
But the problem is, as a beginner, I don't understand how the functions and objects work with each other.
Question 01
I copied the example "Let’s create a movement animation on it’s base:" But my version does not work.
<!DOCTYPE HTML>
<html>
<head>
<style>
.example_path{
position: relative;
width: 600px;
height: 100px;
border-style: solid;
border-width: 5px;
}
.example_block{
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
</head>
<body>
<div onclick="move(this.children[0])" class="example_path">
<div class="example_block"></div>
</div>
<script>
function move(element, delta, duration) {
var to = 500
animate({
delay: 10,
duration: duration || 1000, // 1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
})
}
</script>
</body>
</html>
output console: ReferenceError: animate is not defined
Does anyone know what the problem is?
Question 02
My second wish is, to integrate the easeInOut function
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress) / 2
else
return (2 - delta(2*(1-progress))) / 2
}
}
bounceEaseInOut = makeEaseInOut(bounce)
How can I link both code snippets? The code is also from this page: http://javascript.info/tutorial/animation#maths-the-function-of-progress-delta
Add animate and makeEaseInOut into your script tag then you can use them. You may want to include the functions in a separate JavaScript file eventually.
<script>
function animate(opts) {
var start = new Date
var id = setInterval(function() {
var timePassed = new Date - start
var progress = timePassed / opts.duration
if (progress > 1) progress = 1
var delta = opts.delta(progress)
opts.step(delta)
if (progress == 1) {
clearInterval(id)
}
}, opts.delay || 10)
}
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress) / 2
else
return (2 - delta(2*(1-progress))) / 2
}
}
bounceEaseInOut = makeEaseInOut(bounce)
</script>
that's what I tried.
I still have problems.
output console: delta is not a function. bounce is not a function.
I know I have to learn more about creating functions. But right now I'm not that good to solve the problem.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.example_path{
position: relative;
width: 600px;
height: 100px;
border-style: solid;
border-width: 5px;
}
.example_block{
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<script>
function move(element, delta, duration) {
var to = 500;
animate({
delay: 10,
duration: duration || 1000, // 1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
});
}
function animate(opts) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1) progress = 1
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
}
}, opts.delay || 10);
}
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress)/2;
else
return (2 - delta(2*(1-progress)))/2;
};
}
varbounceEaseInOut = makeEaseInOut(bounce);
</script>
</head>
<body>
<div onclick="move(this.children[0], makeEaseInOut(bounce), 3000)" class="example_path">
<div class="example_block"></div>
</div>
</body>
</html>
I've made a very simple animation using javascript, hope it helps, try to "Run code snippet" for better understanding.
/*JavaScript*/
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
function Back() {
var elem1 = document.getElementById("animate");
var id1 = setInterval(frame2, 5);
var pos1 = 350;
function frame2() {
if (pos1 == 0) {
clearInterval(id1);
} else {
pos1--;
elem1.style.top = pos1 + 'px';
elem1.style.left = pos1 + 'px';
}
}
}
/*CSS*/
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
/*HTML*/
<button onclick="myMove()">Click Me</button>
<button onclick="Back()"> roll back</button>
<div id ="container">
<div id ="animate"></div>
</div>
Related
I have created a simple slider that on scroll scrolls down 100vh. It works perfectly in Safari but it doesn't seem to fire at all in both Chrome or Firefox.
Really appreciate it if anyone could point out to me where i may have gone wrong. I'm sure it's something simple but I just can't figure it out.
I have uploaded the files to my test web server so you can see the issue.
test.liamcrane.co.uk
var slider = document.querySelector('.section__wrapper__inner');
var sections = document.querySelectorAll('.section');
var currentTransform = 0;
var activeSection = 0;
function slideDown() {
if (!(activeSection === sections.length - 1)) {
sectionReset();
currentTransform -= 100;
slider.style.transform = "translate3d(0," + currentTransform + "vh, 0)";
activeSection++;
sections[activeSection].classList.add('active');
}
setTimeout(function() {
ready = true;
}, 2000);
}
function slideUp() {
if (!(activeSection === 0)) {
sectionReset();
currentTransform += 100;
slider.style.transform = "translate3d(0," + currentTransform + "vh, 0)";
activeSection--;
sections[activeSection].classList.add('active');
}
setTimeout(function() {
ready = true;
}, 2000);
}
function sectionReset() {
sections[activeSection].classList.remove('active');
}
var ready = true;
document.addEventListener('scroll', function() {
if (ready && window.pageYOffset > 0) {
ready = false;
slideDown();
} else if (ready && window.pageYOffset <= 0) {
ready = false;
slideUp();
}
});
.section__wrapper {
height: 100vh;
overflow: hidden;
}
.section__wrapper__inner {
height: 100%;
transform: translate3d(0, 0, 0);
transition: transform 1s;
}
.section {
position: relative;
height: 100vh;
color: black;
text-align: center;
}
.section span {
line-height: 100vh;
display:block;
}
<div class="section__wrapper">
<div class="section__wrapper__inner">
<section class="section"><span>1</span></section>
<section class="section"><span>2</span></section>
<section class="section"><span>3</span></section>
<section class="section"><span>4</span></section>
<section class="section"><span>5</span></section>
</div>
</div>
I think is that what you want
I have made a little workarround to force scroll ... maybe a little bit ugly but work see fakeScroll() function bellow.
That force the scrollbar to does not reach the beggining and the end. Because in your example above if the scroll bar reach the end ... scroll event can't be triggered (same if reach the begining).
I have also changed the conditions and the timming from setTimeout (ready = true) to 500. You can change it as you want
Sory for my English.
var slider = document.querySelector('.section__wrapper__inner');
var sections = document.querySelectorAll('.section');
var currentTransform = 0;
var activeSection = 0;
var lastOffset = window.pageYOffset;
var actualOffset = lastOffset;
function fakeScroll(){
if(lastOffset > 1){
window.scrollTo(0,lastOffset - 1);
}else{
window.scrollTo(0,1);
}
}
function slideDown() {
if (!(activeSection === sections.length - 1)) {
sectionReset();
currentTransform -= 100;
slider.style.transform = "translate3d(0," + currentTransform + "vh, 0)";
activeSection++;
sections[activeSection].classList.add('active');
}
fakeScroll();
setTimeout(function() {
ready = true;
}, 500);
}
function slideUp() {
if (!(activeSection === 0)) {
sectionReset();
currentTransform += 100;
slider.style.transform = "translate3d(0," + currentTransform + "vh, 0)";
activeSection--;
sections[activeSection].classList.add('active');
}
fakeScroll();
setTimeout(function() {
ready = true;
}, 500);
}
function sectionReset() {
sections[activeSection].classList.remove('active');
}
var ready = true;
window.addEventListener('scroll', function() {
actualOffset = window.pageYOffset;
if (actualOffset > lastOffset) {
if(ready){
ready = false;
slideDown();
}else{
fakeScroll();
}
} else if (window.pageYOffset <= lastOffset) {
if(ready){
ready = false;
slideUp();
}else{
fakeScroll();
}
}
lastOffset = window.pageYOffset;
});
.section__wrapper {
height: 100vh;
position:relative;
overflow: hidden;
}
.section__wrapper__inner {
height: 100%;
position:relative;
transform: translate3d(0, 0, 0);
transition: transform 1s;
}
.section {
position: relative;
height: 100vh;
color: black;
text-align: center;
}
.section span {
line-height: 100vh;
display:block;
}
<div class="section__wrapper">
<div class="section__wrapper__inner">
<section class="section"><span>1</span></section>
<section class="section"><span>2</span></section>
<section class="section"><span>3</span></section>
<section class="section"><span>4</span></section>
<section class="section"><span>5</span></section>
</div>
</div>
window.addEventListener('scroll', function() {
if (ready && window.pageYOffset > 0) {
ready = false;
slideDown();
} else if (ready && window.pageYOffset <= 0) {
ready = false;
slideUp();
}
});
How do you make JavaScript animation scroll both to the bottom of an element and back to the top? I am still learning about JavaScript and found an example code from w3schools, which, when I modified it to scroll back to the top, worked in the Tryit Editor, using the exact same code for the myUP function I have below. Though I know that in its current state, combined with the other function, this same code is not currently working.
I have a hunch that there was something not good about the code, even when it worked fine by itself in the Tryit Editor. I feel that in the future it would not work properly. Am I right to assume this, and, if so, what should I be doing to achieve this in JavaScript instead?
<html>
<style>
#myContainer {
width: 500px;
height: 500px;
position: relative;
background: black;
}
#tester {
width: 500px;
height: 50px;
position: absolute;
background-color: gray;
}
</style>
<body>
<p>
<button onmousedown="myMove()">DOWN</button>
</p>
<p>
<button onmousedown="myUP()">UP</button>
</p>
<div id ="myContainer">
<div id ="tester"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("tester");
var pos = 0;
var id = setInterval(frame, 20);
function frame() {
if (pos == 500) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
function myUP() {
var elem = document.getElementById("tester");
var pos = 0;
var id = setInterval(frame, 20);
function frame() {
if (pos == 500) {
clearInterval(id);
} else {
pos++;
elem.style.bottom = pos + 'px';
}
}
}
</script>
</body>
Check the working code now,
Your code were making problem in UP function.
function myUP() {
var elem = document.getElementById("tester");
var pos = 500;// Changed the max position.
var id = setInterval(frame, 20);
function frame() {
console.log(pos);
if (pos == 0) { //reverse condition to 0
clearInterval(id);
} else {
pos--; // reverse the position
elem.style.top = pos + 'px'; // that should be back to top
}
}
}
<html>
<style>
#myContainer {
width: 500px;
height: 500px;
position: relative;
background: black;
}
#tester {
width: 500px;
height: 50px;
position: absolute;
background-color: gray;
}
</style>
<body>
<p>
<button onmousedown="myMove()">DOWN</button>
</p>
<p>
<button onmousedown="myUP()">UP</button>
</p>
<div id ="myContainer">
<div id ="tester"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("tester");
var pos = 0;
var id = setInterval(frame, 20);
function frame() {
if (pos == 500) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
function myUP() {
var elem = document.getElementById("tester");
var pos = 500;
var id = setInterval(frame, 5);
function frame() {
console.log(pos);
if (pos == 0) {
clearInterval(id);
} else {
pos--;
elem.style.top = pos + 'px';
}
}
}
</script>
</body>
For teaching myself javascript (and for getting/giving more insight in the field of astronomy :) ), I am setting up a page that displays relative positions of sun and moon.
Right now, the speed of the sun and moon movement is still fixed, but I would really like to make this dynamically user-definable via an input field. So, the initial speed is '30', and a user can speed this up or slow this down. Obviously, the ratio between sun and moon must stay fixed. I tried a lot of things (see some relics in the code, but I can't get it to work.
Anyone with more experience with javascript can assist me in doing this? Also, I notice CPU usage gets very high during this animation. Are there simple steps in making this script more efficient?
var dagen = 0;
function speed($this){
var speedSetting = $this.value;
//alert(speedSetting);
//return per;
}
function periode(bolletje, multiplier=30){
if (bolletje == 'zon'){var per = (multiplier*24/2);}
if (bolletje == 'maan'){var per = (multiplier*24*29.5/2);}
return per;
}
function step(delta) {
elem.style.height = 100*delta + '%'
}
function animate(opts) {
var start = new Date
var id = setInterval(function() {
var timePassed = new Date - start
var progress = timePassed / opts.duration
if (progress > 1) progress = 1
var delta = opts.delta(progress)
opts.step(delta)
if (progress == 1) {
clearInterval(id)
}
}, opts.delay || 10)
}
function terugweg(element, delta, duration) {
var to = -300;
var bolletje = element.getAttribute('id');
per = periode(bolletje);
document.getElementById(bolletje).style.background='transparent';
animate({
delay: 0,
duration: duration || per,
//1 sec by default
delta: delta,
step: function(delta) {
element.style.left = ((to*delta)+300) + "px"
}
});
if(bolletje == 'zon'){
dagen ++;
}
bolletje = element;
document.getElementById('dagen').innerHTML = dagen;
//setInterval(function (element) {
setTimeout(function (element) {
move(bolletje, function(p) {return p})
}, per);
}
function move(element, delta, duration) {
var to = 300;
var bolletje = element.getAttribute('id');
per = periode(bolletje);
document.getElementById(bolletje).style.background='yellow';
animate({
delay: 0,
duration: duration || per,
//1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
});
bolletje = element;
//setInterval(function (element) {
setTimeout(function (element) {
terugweg(bolletje, function(p) {return p})
}, per);
}
hr{clear: both;}
form{display: block;}
form label{width: 300px; float: left; clear: both;}
form input{float: right;}
.aarde{width: 300px; height: 300px; border-radius: 150px; background: url('https://domain.com/img/aarde.png');}
#zon{width: 40px; height: 40px; background: yellow; border: 2px solid yellow; border-radius: 20px; position: relative; margin-left: -20px; top: 120px;}
#maan{width: 30px; height: 30px; background: yellow; border: 2px solid yellow; border-radius: 16px; position: relative; margin-left: -15px; top: 115px;}
<form>
<div onclick="move(this.children[0], function(p) {return p}), move(this.children[1], function(p) {return p})" class="aarde">
<div id="zon"></div>
<div id="maan"></div>
</div>
Dagen: <span id="dagen">0</span>
</form>
<form>
<label><input id="snelheid" type="range" min="10" max="300" value="30" oninput="speed(this)">Snelheid: <span id="snelheidDisplay">30</span></label>
</form>
First, change onlick to oninput in speed input tag.
<input id="snelheid" type="number" value="30" oninput="speed(this)">
And in your speed() function set multiplier = $this.value. multiplier should be global:
var multiplier = 30;
function speed($this){
console.log($this.value);
multiplier = $this.value;
//alert(speedSetting);
//return per;
}
function periode(bolletje){
if (bolletje == 'zon'){var per = (multiplier*24/2);}
if (bolletje == 'maan'){var per = (multiplier*24*29.5/2);}
return per;
}
Here is an example:
https://jsfiddle.net/do4n9L03/2/
Note: multiplier is not speed, it is delay. If you increase it it become slower
I want to change the text after the animation is done but I have a hard time to find something that works. I have tried timers but that dont realy work beacuse the animation time is different every time (will add that later but now it is same every time).
$(document).ready(function () {
$("button").click(function () {
var r = Math.floor(Math.random() * 2) + 1
var moveTime;
if (r == '1') {
moveTime = 5000;
} else if (r == '2') {
moveTime = 4900;
}
var slowDown = 1000;
var $div = $('div').css('left', 0);
while (moveTime > 0) {
slowDown--;
$div.animate({
left: moveTime + "px"
}, 3000);
if (slowDown > 0) {
slowDown--;
moveTime = 0;
}
slowDown--;
moveTime--;
}
document.getElementById("timer").innerHTML = r;
});
});
div {
position: absolute;
float: left;
margin: 200px 0 0 -8400px;
width: 10000px;
height: 125px;
background: repeating-linear-gradient(90deg, #DF0000, #DF0000 125px, #000000 125px, #000000 250px)
}
h1 {
text-align: center;
margin: 130px 0 0 0;
font-size: 90px;
}
body {
overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Start Animation</button>
<div></div>
<h1 id="timer">|</h1>
</body>
You can use the promise() method to map your animations to an array of promises, then use Promise.all() to do something when all have resolved:
var promisesArr = [];
while (moveTime > 0) {
// ...
promisesArr.push($div.animate({
left: moveTime + "px"
}, 3000).promise());
// ...
}
Promise.all(promisesArr).then(function() {
var r = Math.floor(Math.random() * 2) + 1
document.getElementById("timer").innerHTML = r;
});
See Fiddle
see official api for animate
you should be able to just call $(elem).animate().animate() and the second animate will only start when the first ends...
additionally, animate function takes a 'easing' parameter, something like "easein" will probably do what you want without needing to keep track of time at all.
Help! I've no idea what's going wrong here, I'm following along a tutorial video from Tuts+ The code is exact, yet the blue box is not animating to the left.
When I put an alert inside of the moveBox function, I see in the console the alert firing off the same message over and over again.
Here is my test link:
> Trying to animation a blue box left using Javascript <
Here is a screenshot from the video:
Here is my code:
(function() {
var speed = 10,
moveBox = function() {
var el = document.getElementById("box"),
i = 0,
left = el.offsetLeft,
moveBy = 3;
//console.log("moveBox executed " +(i+1)+ " times");
el.style.left = left + moveBy + "px";
if (left > 399) {
clearTimeout(timer);
}
};
var timer = setInterval(moveBox, speed);
}());
HTML:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>JavaScript 101 : Window Object</title>
<style>
#box {
position: abosolute;
height: 100px;
left: 50px;
top: 50px;
width: 100px;
background-color: Blue;
}
</style>
</head>
<body>
<div id="box"></div>
<script src="js/animation.js"></script>
You mispelled "absolute" in your positioning:
#box {
position: absolute; // Your mispelling here
height: 100px;
left: 50px;
top: 50px;
width: 100px;
background-color: Blue;
}
Once I fixed that, it worked fine.
A word of advice -- put a second condition in loops like this so that if the animation fails for some reason you don't end up in an infinite loop. For example, you might have done this:
(function() {
var maxTimes = 1000;
var loopTimes = 0;
var speed = 10,
moveBox = function() {
var el = document.getElementById("box"),
i = 0,
left = el.offsetLeft,
moveBy = 3;
//console.log("moveBox executed " +(i+1)+ " times");
el.style.left = left + moveBy + "px";
loopTimes += 1;
if (left > 399 || loopTimes > maxTimes) {
clearTimeout(timer);
}
};
var timer = setInterval(moveBox, speed);
}());