How can I write this more efficiently?
HTML
<div class="navigation-left">left</div>
<div class="navigation-right">right</div>
Js
$(document).ready(function(){
var offs = 0,
speed = 700;
$('.navigation-left').animate({
left: offs,
opacity: 0
}, speed)
.animate({
left: 70 + offs,
opacity: 100
}, speed)
.animate({
left: offs,
opacity: 0
}, speed)
.animate({
left: 70 + offs,
opacity: 100
}, speed)
.animate({
left: offs,
opacity: 0
}, speed)
.animate({
left: 70 + offs,
opacity: 100
}, speed)
.animate({
left: offs,
opacity: 100
}, speed);
$('.navigation-right').animate({
right: offs,
opacity: 0
}, speed)
.animate({
right: 70 + offs,
opacity: 100
}, speed)
.animate({
right: offs,
opacity: 0
}, speed)
.animate({
right: 70 + offs,
opacity: 100
}, speed)
.animate({
right: offs,
opacity: 0
}, speed)
.animate({
right: 70 + offs,
opacity: 100
}, speed)
.animate({
right: offs,
opacity: 100
}, speed);
});
See the jsfiddle here: http://jsfiddle.net/klawisz/nESMD/
Using jQuery and a setTimeout()
(function anim (times){
$('.left').animate({left:70, opacity:0},700).animate({left:0, opacity:1},700);
$('.right').animate({right:70, opacity:0},700).animate({right:0, opacity:1},700);
if(--times) return setTimeout(anim.bind(this, times), 1400);
}( 5 )); // <--- pass initial N of times
.left, .right {position:absolute; width:50px; height:50px; background:red;}
.left {left:0;}
.right {right:0;}
<div class="left"></div>
<div class="right"></div>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
Something like this?
$(document).ready(function(){
var offs = 0,
speed = 700,
times = 10;
var counter = 0;
var step = function(){
if(counter < times) {
counter++;
$('.navigation-left').animate({
left: offs,
opacity: 0
}, speed)
.animate({
left: 70 + offs,
opacity: 100
}, speed);
$('.navigation-right').animate({
right: offs,
opacity: 0
}, speed)
.animate({
right: 70 + offs,
opacity: 100
}, speed, null, step);
}
};
step();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With