So I\'m making a website with a lot of Divs that take 100% height. And I want to make a button so when it\'s clicked to smoothly scroll to next div. I\'ve coded something s
To make this work you need to identify the currently displayed div
. For that you can apply a class to the element which is currently shown. Then you can use next()
to traverse through them all.
Also note in the below example the addition of a common class on all elements, .p
, in order to DRY up the CSS and make DOM traversal easier.
$(".next").click(function() {
var $target = $('.p.active').next('.p');
if ($target.length == 0)
$target = $('.p:first');
$('html, body').animate({
scrollTop: $target.offset().top
}, 'slow');
$('.active').removeClass('active');
$target.addClass('active');
});
body {
margin: 0;
height: 100%;
}
.p {
height: 100vh;
width: 70%;
}
.p1 {
background-color: #2196F3;
}
.p2 {
background-color: #E91E63;
}
.p3 {
background-color: #01579B;
}
.admin {
background-color: #B71C1C;
height: 100vh;
position: fixed;
right: 0%;
top: 0%;
width: 30%;
float: left;
}