I am trying to automatically loop through and scroll each element from a group of elements to the top of the page with jQuery .next
function. However, the function scrolls just the first element, stops and doesn't loop though.
$(function() {
setInterval(function() {
var $next = $('.per-account:first').next('.per-account');
var $first = $('.per-account:first');
if ($next.length) {
$('html, body').animate({
scrollTop: $next.offset().top
}, 1000);
} else {
$('html, body').animate({
scrollTop: $first.offset().top
}, 1000);
}
}, 3000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 500px; width: 100%; background: red;"> </div>
<div style="height: 500px; width: 100%; background: blue;"> </div>
<div style="height: 500px; width: 100%; background: orange;"> </div>
<div style="height: 500px; width: 100%; background: green;"> </div>
the first element and stops. Any ideas what I am doing wrong here.
My code looks like below:
CodePudding user response:
You're always getting the next element after :first
, which means it's always the second element, not looping.
Add a class to the current element, and then get the next element after that.
$(function() {
setInterval(function() {
var $current = $('.per-account.current')
var $next = $current.next('.per-account');
if (!$next.length) { // wrap around to the beginning
$next = $('.per-account:first');
}
$current.removeClass('current');
$next.addClass('current');
$('html, body').animate({
scrollTop: $next.offset().top
}, 1000);
}, 3000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 500px; width: 100%; background: red;"> </div>
<div style="height: 500px; width: 100%; background: blue;"> </div>
<div style="height: 500px; width: 100%; background: orange;"> </div>
<div style="height: 500px; width: 100%; background: green;"> </div>
CodePudding user response:
The following code will make it work. You were starting from the :first at each interval.
$(function() {
let $current = $('.per-account:first');
const id = setInterval(runInterval, 1000);
function runInterval(){
if ( $current.next('.per-account').length ){
$current = $current.next('.per-account');
$('html, body').animate({
scrollTop: $current.offset().top
}, 500);
} else {
clearInterval(id);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 500px; width: 100%; background: red;"> </div>
<div style="height: 500px; width: 100%; background: blue;"> </div>
<div style="height: 500px; width: 100%; background: orange;"> </div>
<div style="height: 500px; width: 100%; background: green;"> </div>