I have an image gallery I’m using for a webpage. Currently, the gallery images change when the user scrolls, but I’d like to change it so that the images change on a time interval, and are on a loop instead of an up scroll to go back and a down scroll to go forward. I’m pretty new to Javascript, so I’m now sure how to change the below script from scrolling to timed.
JavaScript
x
52
52
1
<script>
2
$(document).ready(function() {
3
var curPage = 1;
4
var numOfPages = $(".skw-page").length;
5
var animTime = 1000;
6
var scrolling = false;
7
var pgPrefix = ".skw-page-";
8
9
function pagination() {
10
scrolling = true;
11
12
$(pgPrefix + curPage).removeClass("inactive").addClass("active");
13
$(pgPrefix + (curPage - 1)).addClass("inactive");
14
$(pgPrefix + (curPage + 1)).removeClass("active");
15
16
setTimeout(function() {
17
scrolling = false;
18
}, animTime);
19
};
20
21
function navigateUp() {
22
if (curPage === 1) return;
23
curPage--;
24
pagination();
25
};
26
27
function navigateDown() {
28
if (curPage === numOfPages) return;
29
curPage++;
30
pagination();
31
};
32
33
$(document).on("mousewheel DOMMouseScroll", function(e) {
34
if (scrolling) return;
35
if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
36
navigateUp();
37
} else {
38
navigateDown();
39
}
40
});
41
42
$(document).on("keydown", function(e) {
43
if (scrolling) return;
44
if (e.which === 38) {
45
navigateUp();
46
} else if (e.which === 40) {
47
navigateDown();
48
}
49
});
50
});
51
</script>
52
Advertisement
Answer
Just call setInterval, change what happens when navigateDown
is called once all pages have been cycled through, and remove the scroll/keydown listeners.
JavaScript
1
31
31
1
$(document).ready(function() {
2
var curPage = 1;
3
var numOfPages = $(".skw-page").length;
4
var animTime = 1000;
5
var scrolling = false;
6
var pgPrefix = ".skw-page-";
7
8
function pagination() {
9
scrolling = true;
10
11
$(pgPrefix + curPage)
12
.removeClass("inactive")
13
.addClass("active");
14
$(pgPrefix + (curPage - 1)).addClass("inactive");
15
$(pgPrefix + (curPage + 1)).removeClass("active");
16
if (curPage === 1) $(pgPrefix + numOfPages).addClass("inactive");
17
18
setTimeout(function() {
19
scrolling = false;
20
}, animTime);
21
}
22
23
function navigateDown() {
24
if (curPage === numOfPages) curPage = 0;
25
curPage++;
26
console.log(curPage);
27
pagination();
28
}
29
30
setInterval(navigateDown, 5000); // 5000 ms == 5 s
31
});
JavaScript
1
7
1
.active {
2
color: purple;
3
}
4
5
.inactive {
6
display: none;
7
}
JavaScript
1
8
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<div>
4
<p class="skw-page skw-page-1 active">Page 1</p>
5
<p class="skw-page skw-page-2 inactive">Page 2</p>
6
<p class="skw-page skw-page-3 inactive">Page 3</p>
7
<p class="skw-page skw-page-4 inactive">Page 4</p>
8
</div>