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.
Related
I have a simple animation code, looks like a console input.
Originally from: https://codepen.io/atunnecliffe/pen/BaZyLR
I modified the splash screen intro into just a console input in my website:
Code:
<script>
//console
var textarea = $('.term');
var text = 'ping life';
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(
function () {
runner();
}, Math.floor(Math.random() * 1000) + 50);
}
</script>
Now the effect that I want is a bit complex, for me at least, as my knowledge about JQuery is limited. I wanted the code to enter ping life, then backspace completely, repeat infinitely. I looked up on how to simulate backspace in JQuery, using escape sequence of (8), but I am not sure how to use the escape sequence, nor implement the function into the existing recursive function, for it to repeat infinitely.
Any help would be wonderful :)
Like this?
Counting like this will give a zigzag like counting pattern. I added buffers for start and end of input, and a fixed timeout for deleting letters.
textarea.text(text.substr(0, i)) selects a substring of your text (treated as an array of letters - selecting everything between index 0 and i)
Easier than appending and deleting letters
var direction = 1;
var i = 0;
var textarea = $('.term');
var text = 'ping life';
// NOTE:
// I added the "#dev:~$ " as css:before elem, easier to write the code
function count() {
i += direction;
direction *= (((i % text.length) == 0) ? -1 : 1);
textarea.text(text.substr(0, i));
clearInterval(time);
// direction is 1 if counting up
if (direction === 1) {
if (i === 0) {
// buffer for start
time = setInterval(count, 1000);
} else {
time = setInterval(count, Math.floor(Math.random() * 1000) + 50);
}
} else {
// direction is -1 if counting down
if (i === text.length) {
time = setInterval(count, 1500);
} else {
// buffer for end
time = setInterval(count, 100);
}
}
}
// inital interval
// setTimeout doesn't work well here
var time = setInterval(count, 1000)
html,
body {
margin: 0 auto;
height: 100%;
}
pre {
padding: 0;
margin: 0;
}
pre::before {
content: "#dev:~$ ";
color: white;
}
.load {
margin: 0 auto;
min-height: 100%;
width: 100%;
background: black;
}
.term {
font-family: monospace;
color: #fff;
opacity: 0.8;
font-size: 2em;
overflow-y: auto;
overflow-x: hidden;
padding-top: 10px;
padding-left: 20px;
}
.term:after {
content: "_";
opacity: 1;
animation: cursor 1s infinite;
}
#keyframes cursor {
0% {
opacity: 0;
}
40% {
opacity: 0;
}
50% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="load">
<pre class="term"></pre>
</div>
So I an trying to have multiple background image changes on click using javascript.
Can anyone help here I am trying to change multiple background images with a click, with this code I am getting 2 image changes but somewhere at the function updateIndex I can't work out how to make it continuous throughout multiple images.
Thanks a lot in advance!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<div id="body" class="imageOne"></div>
<style>
html,
body, {
height: 100%;
width: 100%;
}
#body.imageOne {
background-image: url("first.svg");
}
#body.imageTwo {
background-image: url("2.svg");
}
#body.imageThree {
background-image: url("3.svg");
}
#body.imageFour {
background-image: url("first.svg");
}
</style>
<script>
var bodyObj, className, index;
// all background images, calling them to change
bodyObj = document.getElementById('body');
index = 1;
className = [
'imageOne',
'imageTwo',
'imageThree',
'imageFour',
];
function updateIndex() {
if (index === 0) {
index = 1;
} else {
index = 1;
index = 2;
}
}
bodyObj.onclick = function(e) {
e.currentTarget.className = className[index];
updateIndex();
}
</script>
Set the index to 0
and in order to loop use ++index % className.length
const className = ['imageOne','imageTwo','imageThree','imageFour'];
let index = 0;
function updateClassName() {
this.className = className[++index % className.length];
}
document.getElementById('body').addEventListener("click", updateClassName);
html, body{height: 100%;width: 100%; margin:0;}
#body{ height: calc(100% - 4rem); background: center / cover; }
#body.imageOne {background-image: url("//placehold.co/800x600/0bf/fff");}
#body.imageTwo {background-image: url("//placehold.co/800x600/f0b/fff");}
#body.imageThree {background-image: url("//placehold.co/800x600/b0f/fff");}
#body.imageFour {background-image: url("//placehold.co/800x600/fb0/fff");}
Click the image
<div id="body" class="imageOne"></div>
The issue is due to the logic in the updateIndex() function. You only set the index to 0, or to 1, then for some reason 2 immediately. It doesn't cycle around.
To fix the logic you can simply increment the index on each successive click. Try this:
var bodyObj = document.getElementById('body'),
index = 1,
className = ['imageOne', 'imageTwo', 'imageThree', 'imageFour']; // remove trailing comma here
function updateIndex() {
index = ++index % className.length;
}
bodyObj.addEventListener('click', function(e) {
e.currentTarget.className = className[index];
updateIndex();
});
#body {
height: 250px;
width: 250px;
}
#body.imageOne { background-image: url("https://dummyimage.com/250/000000/ffffff"); }
#body.imageTwo { background-image: url("https://dummyimage.com/250/cc0000/000000"); }
#body.imageThree { background-image: url("https://dummyimage.com/250/00cc00/000000"); }
#body.imageFour { background-image: url("https://dummyimage.com/250/0000cc/000000"); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body" class="imageOne"></div>
Also note the use of addEventListener() over the outdated onclick.
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>
I'm using the following code to run a slider. The function runs well.
How do I make a simple fadein effect with js. No jQuery.
Also setInterval waits 5 seconds before displaying the first image. How do I start with an image and then continue with the 5 second interval?
var i = 0;
var hello = function(){
if(i<image.length)
{document.getElementById('fullscreenImage').src = image[i];
i+=1;
}
else i = 0;
}
setInterval(hello,5000);
#fullscreenImage {
z-index: -999;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-size: cover;
}
<img id="fullscreenImage"></img>
You can do this by progressively adjusting the opacity style property of an image. Here's a simple example: declare some HTML structure, then wire the sliding behavior, using the makeSlider() function, passing an array containing the target images, as well as fading parameters.
HTML file example (whatever.html) :
<head>
<style type="text/css">
img {
position: absolute;
top: 0;
left: 0;
width: 300px;
visibility: hidden;
}
img:first-child {
visibility: visible;
}
</style>
<script type="text/javascript" src="slider.js"></script>
</head>
<body>
<img src="1.jpg" alt="Alt 1" />
<img src="2.jpg" alt="Alt 2" />
<script type="text/javascript">
var fadeInterval = 3000;
var fadeStep = 20;
setTimeout(function() {
makeSlider([document.images[0], document.images[1]], fadeInterval, fadeStep);
}, fadeInterval);
</script>
</body>
Javascript file (slider.js):
function makeSlider(pictures, fadeInterval, fadeStep) {
var currentIndex = 0;
function show() {
var nextIndex = (currentIndex + 1) % pictures.length;
var current = pictures[currentIndex];
var next = pictures[nextIndex];
fade(current, 1, -0.1, function() {
current.style.visibility = "hidden";
next.style.visibility = "visible";
fade(next, 0, +0.1, function() {
currentIndex = nextIndex;
setTimeout(function() { show(); }, fadeInterval);
});
});
}
function fade(element, origin, step, continuation) {
element.style.opacity = origin;
setTimeout(function () {
var nextOrigin = Math.round((origin + step) * 10) / 10;
if (nextOrigin >= 0 && nextOrigin <= 1) {
fade(element, nextOrigin, step, continuation);
} else {
continuation();
}
}, fadeStep);
}
show();
}
HTH.
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);
}());