I want to loop the class name 'move' over all the divs, so if the first div has the class name 'move', i want to remove it and then add it to the next element in every three seconds
$(document).ready(function () {
setInterval(swapUsp, 3000);
function swapUsp() {
var active = $('#infobarContainer .uspTag');
var next = ($('#infobarContainer .uspTag').next().length > 0) ? $('#infobarContainer .uspTag').next() : $('#infobarContainer .uspTag:first');
if (active.hasClass('move')) {
active.removeClass('move')
next.addClass('move');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="infobarContainer">
<div >
USP 1
</div>
<div >
USP 2
</div>
<div >
USP 3
</div>
<div >
USP 4
</div>
</div>
CodePudding user response:
You can change your ready function to
$(document).ready(function () {
setInterval(swapUsp, 3000);
function swapUsp() {
var active = $('#infobarContainer .uspTag.move').first();
var next = ($('#infobarContainer .uspTag.move').next().length > 0) ? $('#infobarContainer .uspTag.move').next() : $('#infobarContainer .uspTag:first');
active.removeClass('move')
next.addClass('move');
}
});
CodePudding user response:
Here's one with less DOM queries
const startAnimation = (time) => {
let counter = 0;
const elements = $('.uspTag');
const update = () => {
const index = counter % elements.length;
const previousIndex = counter % elements.length;
$(elements[index]).toggleClass('move');
$(elements[previousIndex]).toggleClass('move');
}
setInterval(update, 3000);
}
startAnimation(3000)