Using setInterval to create a progress bar - javascript

I was hoping a kind soul might be able to assist.
I have a slideshow which auto-plays, my intention is to have the next button act as a visual aid, highlighting the when the next frame is coming in.
sync with the autoPlay interval.
Right now, the update func concludes too early, which is the best I have managed to do. Typically I have the clearInterval and setInterval conflicting creating shuddering animations.
What am I doing wrong?
<!doctype html>
<html lang="en">
<head>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
.carousel_wrapper {
height: 50vh;
width: 100%;
position: relative;
}
.carousel_frame {
width: 100%; height: 100%;
}
.carousel_controls {
position: absolute;
bottom: 0;
left: 0;
}
.prev, .next {
height: 50px;
width: 100px;
background: aqua;
display: inline-block;
}
.next {
background: linear-gradient(to right, white 0%, aqua);
}
.carousel_frame:nth-child(1) {
background: red;
}
.carousel_frame:nth-child(2) {
background: blue;
}
.carousel_frame:nth-child(3) {
background: green;
}
</style>
<script>
window.addEventListener('DOMContentLoaded', () => {
const homepage_carousel = new carousel();
});
function carousel() {
const carousel = document.getElementsByClassName('.carousel_wrapper')[0];
const frames = [...document.getElementsByClassName('carousel_frame')];
const prev_button = document.getElementsByClassName('prev')[0];
const next_button = document.getElementsByClassName('next')[0];
this.frameIndex = 1;
prev_button.addEventListener('click', () => {
this.resetPlay();
this.move(-1);
})
next_button.addEventListener('click', () => {
this.resetPlay();
this.move(+1);
})
this.hideAll = () => {
frames.forEach((f) => {
f.style.display = 'none';
});
}
this.show = () => {
this.hideAll();
frames[this.frameIndex - 1].style.display = 'block';
this.update_bg();
}
this.move = (amount) => {
this.frameIndex += amount;
this.frameIndex = (this.frameIndex > frames.length ? 1 : (this.frameIndex < 1) ? frame.lengh : this.frameIndex);
this.show();
}
this.update_bg = () => {
let w = 1;
let test = setInterval(adjust, 10);
function adjust() {
if (w >= 100) {
clearInterval(test);
w = 0;
} else {
w++;
next_button.style.backgroundImage = `linear-gradient(to right, white ${w}%, aqua)`
}
}
setInterval(adjust, 3000);
}
this.autoPlay = () => {
this.move(+1)
this.update_bg();
}
this.resetPlay = () => {
// clearInterval(timer);
// timer = setInterval(this.autoPlay(), 4000);
}
this.show();
const timer = setInterval(this.autoPlay, 3000);
}
</script>
</head>
<body>
<div class='carousel_wrapper'>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_controls'>
<span class='prev'>Previous</span>
<span class='next'>
Next
</span>
</div>
</div>
</body>
</html>

Related

How Can I make this touch Slider move atomically?

I am trying to make this touch slider, which move between slides automatically.
I tried many ways but nothing helped, this bellow is my Code:
.slider-container {
height: 100vh;
display: inline-flex;
overflow: hidden;
scrollbar-width: none;
transform: translateX(0);
will-change: transform;
transition: transform 0.3s ease-out;
cursor: grab;
}
.slide{
max-height: 100vh;
width: 100vw;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
<div class="slider-container">
<div class="slide">
<img src="pics/slider/127616685-multi-colored-samples-of-marble-granite-and-travertine-chips-and-pebbles-for-landscape-design-close-.jpg"/>
</div>
<div class="slide">
<img src="pics/slider/1554689647283.jpg"/>
</div>
</div>
Just add this code at the bottom of your JS code.
This code changes the value of currentTranslate every 1 second and then calls the touchEnd(); function.
**I added the variable "loop" if the value is true when the last slide is reached... the script will call the first one again and so on indefinitely. If it has a value of false when the last slide is reached, the interval will be removed. And scrolling the slides will stop.
var loop = true; //<-- "true" Loop or "false" Stop on the End
var slideShw = setInterval(() => {
currentTranslate = currentTranslate - 101;
touchEnd();
if (currentIndex === slides.length - 1) {
if (loop) {
currentIndex -= slides.length;
} else {
stop_slideShw();
}
}
}, 1000);
function stop_slideShw() {
clearInterval(slideShw);
}
Example:
// get our elements
const slider = document.querySelector('.slider-container'),
slides = Array.from(document.querySelectorAll('.slide'))
// set up our state
let isDragging = false,
startPos = 0,
currentTranslate = 0,
prevTranslate = 0,
animationID,
currentIndex = 0
// add our event listeners
slides.forEach((slide, index) => {
const slideImage = slide.querySelector('img')
// disable default image drag
slideImage.addEventListener('dragstart', (e) => e.preventDefault())
// touch events
slide.addEventListener('touchstart', touchStart(index))
slide.addEventListener('touchend', touchEnd)
slide.addEventListener('touchmove', touchMove)
// mouse events
slide.addEventListener('mousedown', touchStart(index))
slide.addEventListener('mouseup', touchEnd)
slide.addEventListener('mousemove', touchMove)
slide.addEventListener('mouseleave', touchEnd)
})
// make responsive to viewport changes
window.addEventListener('resize', setPositionByIndex)
// // prevent menu popup on long press
// window.oncontextmenu = function (event) {
// event.preventDefault()
// event.stopPropagation()
// return false
// }
function getPositionX(event) {
return event.type.includes('mouse') ? event.pageX : event.touches[0].clientX
}
// use a HOF so we have index in a closure
function touchStart(index) {
return function (event) {
currentIndex = index
startPos = getPositionX(event)
isDragging = true
animationID = requestAnimationFrame(animation)
slider.classList.add('grabbing')
}
}
function touchMove(event) {
if (isDragging) {
const currentPosition = getPositionX(event)
currentTranslate = prevTranslate + currentPosition - startPos
}
}
var movedBy;
function touchEnd() {
cancelAnimationFrame(animationID)
isDragging = false
movedBy = currentTranslate - prevTranslate
// if moved enough negative then snap to next slide if there is one
if (movedBy < -100 && currentIndex < slides.length - 1) currentIndex += 1
// if moved enough positive then snap to previous slide if there is one
if (movedBy > 100 && currentIndex > 0) currentIndex -= 1
setPositionByIndex()
slider.classList.remove('grabbing')
}
function animation() {
setSliderPosition()
if (isDragging) requestAnimationFrame(animation)
}
function setPositionByIndex() {
currentTranslate = currentIndex * -window.innerWidth
prevTranslate = currentTranslate
setSliderPosition()
}
function setSliderPosition() {
slider.style.transform = `translateX(${currentTranslate}px)`
}
// NEW LINES /////////////////////////////////////////
var loop = true; //<-- "true" Loop or "false" Stop on the End
var slideShw = setInterval(() => {
currentTranslate = currentTranslate - 101;
touchEnd();
if (currentIndex === slides.length - 1) {
if (loop) {
currentIndex -= slides.length;
} else {
stop_slideShw();
}
}
}, 1000);
function stop_slideShw() {
clearInterval(slideShw);
}
/* :root {
--shadow: rgba(0, 0, 0, 0.8)
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
*/
.slider-container {
height: 100vh;
display: inline-flex;
overflow: hidden;
scrollbar-width: none;
transform: translateX(0);
will-change: transform;
transition: transform 0.3s ease-out;
cursor: grab;
}
.slide {
max-height: 100vh;
width: 100vw;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
#media(min-width: 1200px) {
.slide {
padding: 3rem;
}
}
.slide img {
max-width: 100%;
max-height: 100%;
transition: transform 0.3s ease-in-out;
box-shadow: 5px 5px 50px -1px var(--shadow);
border-radius: 4px;
user-select: none;
}
.grabbing {
cursor: grabbing;
}
.grabbing .slide img {
transform: scale(0.9);
box-shadow: 5px 5px 40px -1px var(--shadow);
}
<div class="slider-container">
<div class="slide">
<img
src="https://images.pexels.com/photos/145939/pexels-photo-145939.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" />
</div>
<div class="slide">
<img
src="https://images.pexels.com/photos/47547/squirrel-animal-cute-rodents-47547.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" />
</div>
<div class="slide">
<img
src="https://thumbor.forbes.com/thumbor/960x0/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5faad4255239c9448d6c7bcd%2FBest-Animal-Photos-Contest--Close-Up-Of-baby-monkey%2F960x0.jpg%3Ffit%3Dscale" />
</div>
</div>
To move your slider automatically you should use the animation property.
Its difficult to work on slider without Javascript. I am giving some fresh codes, you can check them and rewrite your codes accordingly.
var photos = ["1.png","2.png","3.png"]
var time = 3000;
var imgTag = document.querySelector("img")
var count = 0;
function changeImg() {
document.slide.src = photos[count];
count++;
if(count==3){
count=0;
imgTag.src = photos[count];
}
else{
imgTag.src = photos[count];
}
console.log("lap");
setTimeout("changeImg()",time);
}
window.onload = changeImg;
function next(){
count++;
time=3000;
if(count==3){
count=0;
imgTag.src = photos[count];
}
else{
imgTag.src = photos[count];
}
console.log("next");
}
function prev(){
count--;
time=3000;
if(count==-1){
count=2;
imgTag.src = photos[count];
}
else{
imgTag.src = photos[count];
}
console.log("prev");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stack Overflow</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button onclick="prev()">Prev</button>
<img src="1.png" name="slide" alt="" height="300" width="300">
<button onclick="next()">Next</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
Put any 3 images named "1.png" "2.png" "3.png". And then run the code. Hopefully it will run, and you will get an idea. Here I have used a setTimeout function that will fire up after 3 seconds to change your slides.
Thank you.

How to make the element stop falling?

Below this text is my code - I am trying to create the chrome dino game, and so far everything is going well, but I have one problem - after the red block jumps, the dino doesn't stop falling down - while it should. I don't understand where my problem is, as I wrote about the same code yesterday and everything worked just fine. The gravity function can be found in the JavaScript under // Gravity.
Notice how it's code is very similar to the jump function, but it doesn't work as good as the jump function. Any help would be appreciated!!!!!
// HTML Elements + Other Variables
const floor1 = document.getElementById("floor1");
const floor2 = document.getElementById("floor2");
const floor3 = document.getElementById("floor3");
const floor4 = document.getElementById("floor4");
const floor5 = document.getElementById("floor5");
const floor6 = document.getElementById("floor6");
const floor7 = document.getElementById("floor7");
const dino = document.getElementById("dino");
const highBird = document.getElementById("highBird");
const lowBird = document.getElementById("lowBird");
const wideCactus = document.getElementById("wideCactus");
const thinCactus = document.getElementById("thinCactus");
let jump = 0;
// Floor Function
setTimeout(function () {
floor1.classList.add("floor1Animation");
}, 0);
setTimeout(function () {
floor2.classList.add("floor2Animation");
}, 1000);
setTimeout(function () {
floor3.classList.add("floor3Animation");
}, 2000);
setTimeout(function () {
floor4.classList.add("floor4Animation");
}, 3000);
setTimeout(function () {
floor5.classList.add("floor5Animation");
}, 4000);
setTimeout(function () {
floor6.classList.add("floor6Animation");
}, 5000);
setTimeout(function () {
floor7.classList.add("floor7Animation");
}, 6000);
// Jump
document.onkeydown = function (event) {
let key = event.key;
if (key == "ArrowUp") {
let jumpCount = 0;
if (dino.offsetTop == 95) {
let jumpInterval = setInterval(function () {
dino.style.top = (dino.offsetTop - 5) + "px";
jumpCount += 1;
jump = true;
if (jumpCount == 20) {
clearInterval(jumpInterval);
jump = false;
jumpCount = 0;
}
}, 10);
}
}
}
// Gravity
setInterval(function () {
if (jump == false) {
let jumpGravity = setInterval(function () {
dino.style.top = (dino.offsetTop + 5) + "px";
}, 10);
if (dino.offsetTop == 95) {
clearInterval(jumpGravity);
}
}
}, 10);
body {
margin: 0;
padding: 0;
justify-content: center;
align-items: center;
display: flex;
width: 100vw;
height: 100vh;
}
#gameBoard {
width: 1000px;
height: 150px;
border: 2px solid black;
overflow: hidden;
margin: auto;
position: relative;
background-color: white;
}
#dino {
width: 30px;
height: 50px;
background-color: red;
left: 10px;
top: 95px;
position: absolute;
}
.floorBackground {
position: relative;
height: 10px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.floor {
position: absolute;
top: 140px;
height: 10px;
width: 200px;
}
#floor1 {
right: -200px;
background-color: red;
}
.floor1Animation {
animation: floorAnimation 6s infinite linear;
}
#floor2 {
right: -200px;
background-color: blue;
}
.floor2Animation {
animation: floorAnimation 6s infinite linear;
}
#floor3 {
right: -200px;
background-color: green;
}
.floor3Animation {
animation: floorAnimation 6s infinite linear;
}
#floor4 {
right: -200px;
background-color: purple;
}
.floor4Animation {
animation: floorAnimation 6s infinite linear;
}
#floor5 {
right: -200px;
background-color: brown;
}
.floor5Animation {
animation: floorAnimation 6s infinite linear;
}
#floor6 {
right: -200px;
background-color: orange;
}
.floor6Animation {
animation: floorAnimation 6s infinite linear;
}
#floor7 {
right: -200px;
background-color: yellow;
}
.floor7Animation {
animation: floorAnimation 6s infinite linear;
}
#keyframes floorAnimation {
from {
right: -200px;
}
to {
right: 1000px;
}
}
#keyframes jumping {
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>
Dino Game
</title>
<link rel = "stylesheet" type = "text/css" href = "DinoCSS.css">
</head>
<body>
<div id = "gameBoard">
<div id = "floor1" class = "floor">
<img src = "Pictures/dinoBackground.PNG" class = "floorBackground">
</div>
<div id = "floor2" class = "floor">
<img src = "Pictures/dinoBackground.PNG" class = "floorBackground">
</div>
<div id = "floor3" class = "floor">
<img src = "Pictures/dinoBackground.PNG" class = "floorBackground">
</div>
<div id = "floor4" class = "floor">
<img src = "Pictures/dinoBackground.PNG" class = "floorBackground">
</div>
<div id = "floor5" class = "floor">
<img src = "Pictures/dinoBackground.PNG" class = "floorBackground">
</div>
<div id = "floor6" class = "floor">
<img src = "Pictures/dinoBackground.PNG" class = "floorBackground">
</div>
<div id = "floor7" class = "floor">
<img src = "Pictures/dinoBackground.PNG" class = "floorBackground">
</div>
<div id = "dino"></div>
<div id = "highBird"></div>
<div id = "lowBird"></div>
<div id = "wideCactus"></div>
<div id = "thinCactus"></div>
</div>
<script type = "text/javascript" src = "DinoJS.js"></script>
</body>
</html>
You should try simplifying your code, it may make the issue easier to find or it may even remove it entirely.
I'd suggest using a velocity system, where every frame you adjust the dino's offsetTop by the dino's current velocity, and then subtract the gravity amount from the dino's current velocity.
This causes the velocity to decrease at a constant rate, but the dino's offsetTop position to decrease at an exponential pace, mimicking real gravity.
Then, to make collision work, just test if the dino is at or above the correct "offsetTop" value before subtracting the gravity. If you find that the dino is below the ground, just set the offsetTop to the ground level and clear the velocity.
I'd also suggest moving your game over to the HTML5 Canvas API, since then you just have to deal with properties of objects rather than DOM element style attributes.
Velocity example with canvas:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 10;
var y = 10;
var VelocityX = 0;
var VelocityY = 0;
const gravity = 0.75;
// width and height of the square
var width = 10;
var height = 10;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
x += VelocityX;
if( x > 500) {
x = 0;
}
if ( y >= 450 ) {
y = 450
VelocityY = 0
} else {
y += VelocityY;
VelocityY += gravity; // Higher values = lower position on canvas
}
ctx.fillRect(x, y, width, height);
}
setInterval(animate, 1000 / 60); // 60 FPS
#canvas {
border: 1px solid black;
}
<canvas id="canvas" width="500" height="500"></canvas>
JSFiddle

Why does my <div> element start shaking when I try to move it?

I'm new to Stack Overflow.
I have a simple webpage which tries to move a colored div element back and forth.
However when I run it the div element starts moving correctly but after a few seconds it starts shaking madly, as if its boss refused to give it the salary.
Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Move</title>
<link rel="stylesheet" href="D:\Web\CSS\CSS.css"/>
<script src="D:\Web\JS\JS.js">
</script>
</head>
<body>
<div id="container">
<div id="box">
</div>
</div>
</body>
</html>
JavaScript:
window.onload = function() {
var x = 0;
var box = document.getElementById("box");
setInterval(moveRight, 5);
function moveRight() {
if(x >= 150) {
clearInterval();
setInterval(moveLeft, 5);
} else {
x += 1;
box.style.left = x + "px";
}
}
function moveLeft() {
if(x <= 0) {
clearInterval();
setInterval(moveRight, 5);
} else {
x -= 1;
box.style.left = x + "px";
}
}
}
CSS:
body {
background-color: #246;
}
#container {
width: 200px;
height: 50px;
background: #268;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: #2ac;
position: absolute;
}
Plz help me
Thanks
You're not clearing the interval since you're not passing a variable to it, therefore it's not doing anything. If you set the interval to a variable, you can clear the interval when you switch the direction.
Reference: https://www.w3schools.com/jsref/met_win_clearinterval.asp
Here's an example:
(function() {
var direction;
var x = 0;
var box = document.getElementById("box");
// set the initial direction
direction = setInterval(moveRight, 5);
function moveRight() {
if (x >= 150) {
clearInterval(direction);
direction = setInterval(moveLeft, 5);
} else {
x += 1;
box.style.left = x + "px";
}
}
function moveLeft() {
if (x <= 0) {
clearInterval(direction);
direction = setInterval(moveRight, 5);
} else {
x -= 1;
box.style.left = x + "px";
}
}
})();
body {
background-color: #246;
}
#container {
width: 200px;
height: 50px;
background: #268;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: #2ac;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<title>Move</title>
</head>
<body>
<div id="container">
<div id="box">
</div>
</div>
</body>
</html>

Javascript Slideshow with play pause and Next Prev button

I'm making a slideshow in Javascript with a Play / Pause and Next / Prev. I have manage to slideshow working with play/pause button, but now i wanted to add Next and Prev button to it. Can some one please help me how can i do that.
Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple HTML Slideshow</title>
<style type="text/css">
#slideshow {
margin: 50px auto;
position: relative;
width: 900px;
height: 450px;
padding: 10px;
}
#slideshow > div {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
}
#slideshow > div > img {
width: 100%;
}
#button { text-align: center; }
</style>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</head>
<body>
<div id="slideshow">
<div>
<img name="slide" id="imgSlideshow" src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg">
</div>
</div>
<div id="button">
Prev
Play/Pause
Next
</div>
</body>
</html>
Here is JavaScript:
<script language="javascript" type="text/javascript">
var i = 0;
var path = new Array();
//var timer = setInterval("slide()",2000);
var timer;
// LIST OF IMAGES
path[0] = "http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg";
path[1] = "http://themarklee.com/wp-content/uploads/2013/12/starlight.jpg";
path[2] = "http://themarklee.com/wp-content/uploads/2013/12/snowstorm.jpg";
path[3] = "http://themarklee.com/wp-content/uploads/2013/12/misty-winter-afternoon.jpg";
function slide() {
document.getElementById("imgSlideshow").src = path[i];
i = (i + 1)%path.length;
//console.log(i);
}
function setTimer(){
if (timer) {
// stop
clearInterval( timer );
timer=null;
}
else {
timer = setInterval("slide()",2000);
}
}
var imgNumber = 1;
var numberOfImg = path.length;
function previousImage() {
if(imgNumber > 1) {
imgNumber--;
}
else {
imgNumber = numberOfImg;
}
document.getElementById("imgSlideshow").src = path[imgNumber-1];
changeCounter(imgNumber, numberOfImg);
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.getElementById("imgSlideshow").src = path[imgNumber-1];
changeCounter(imgNumber, numberOfImg);
}
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
document.getElementById("counter").innerHTML = 1 + "/" + path.length;
</script>
Any Help is appreciated and thanks in advance.
Only minor changes in the logic.
var imgNumber = 0;
var path = ["http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg",
"http://themarklee.com/wp-content/uploads/2013/12/starlight.jpg",
"http://themarklee.com/wp-content/uploads/2013/12/snowstorm.jpg",
"http://themarklee.com/wp-content/uploads/2013/12/misty-winter-afternoon.jpg"
];
var numberOfImg = path.length;
var timer = null;
function slide() {
imgNumber = (imgNumber + 1) % path.length;
console.log(imgNumber);
document.getElementById("imgSlideshow").src = path[imgNumber];
changeCounter(imgNumber + 1, numberOfImg);
}
function setTimer() {
if (timer) {
clearInterval(timer);
timer = null;
} else {
timer = setInterval(slide, 2000);
}
return false;
}
function previousImage() {
--imgNumber;
if (imgNumber < 0) {
imgNumber = numberOfImg - 1;
}
document.getElementById("imgSlideshow").src = path[imgNumber];
changeCounter(imgNumber + 1, numberOfImg);
return false;
}
function nextImage() {
++imgNumber;
if (imgNumber > (numberOfImg - 1)) {
imgNumber = 0;
}
document.getElementById("imgSlideshow").src = path[imgNumber];
changeCounter(imgNumber + 1, numberOfImg);
return false;
}
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
document.getElementById("counter").innerHTML = 1 + "/" + path.length;
#slideshow {
margin: 50px auto;
position: relative;
width: 900px;
height: 450px;
padding: 10px;
}
#slideshow > div {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
}
#slideshow > div > img {
width: 100%;
}
#button {
text-align: center;
}
<div id="slideshow">
<div>
<img name="slide" id="imgSlideshow" src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg">
</div>
</div>
<div id="button">
Prev
Play/Pause
Next
</div>
<div id="counter"></div>

Clear a GSAP TimelineMax animation after reversing it

Basically I have a structure like this, my goal is to animate 4 divs so that when you click on one the other slide out and when you click on the container they return to their initial positions.
var TL = new TimelineMax;
$('.quater').on('click', function () {
$faders = $('.container').find('.quater').not(this),
$faders.each(function () {
TL.to($(this), 1, {autoAlpha:0, x:50}, 0);
});
});
$('.container').on('click', function () {
TL.reverse();
TL.clear();
});
The problem is that if I omit the "TL.clear();" it will work just for the first ".quater" div clicked, if i put in the "TL.clear();" the animation will not reverse anymore.
jsFiddle.
Snippet:
var container = document.querySelector('.container');
var items = document.querySelectorAll('.item');
var duration = 0.6;
var ease = Expo.easeOut;
var numItems = items.length;
var i;
container.addEventListener('click', onContainerClicked, false);
for (i = 0; i < numItems; i += 1) {
(function(index){
items[index].timeline = new TimelineMax({ paused: true });
items[index].timeline.fromTo(items[index], duration, { y: 0, autoAlpha: 0.4 }, { y: -104, autoAlpha: 1, ease: ease });
items[index].addEventListener('click', onItemClicked, false);
}(i));
}
function onContainerClicked() { reverseAll(); }
function onItemClicked(e) {
reverseAll();
e.target.timeline.play();
}
function reverseAll() {
for (i = 0; i < numItems; i += 1) { items[i].timeline.reverse(); }
}
html, body {
margin: 0;
padding: 0;
}
.container {
background: #444;
width: 512px;
height: 104px;
}
.item {
float: left;
margin: 2px 0 0 2px;
width: 100px;
height: 100px;
}
.item:nth-child(odd) { background: #0cc; }
.item:nth-child(even) { background: #cc0; }
<script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js"></script>
<div class="container"></div>
<div class="item"> </div>
<div class="item"> </div>
<div class="item"> </div>
<div class="item"> </div>
<div class="item"> </div>

Categories