Reputation: 990
I have this code to scroll the viewport height section-by-section when clicked on a fixed button until the end is reached. Then I want to fadeOut the button.
The HTML
<a class="cd-go">
<img class="scroll-swipe" src="<?php bloginfo('template_directory'); ?>/img/scroll_down_arrow.svg">
</a><!-- scroll btn -->
The js:
$(document).on('click', '.cd-go', function(event){
event.preventDefault();
var viewportHeight = $(window).height();
$('html, body').animate({
scrollTop: viewportHeight,
complete: function () {
$('.cd-go').fadeOut(300);
}
}, 500);
});
The problem is it is only scrollin from first to second section. How could this be section by section until the bottom?
EDIT: Here's a fiddle: http://jsfiddle.net/cyt57dsj/7/
Upvotes: 2
Views: 1116
Reputation: 5434
You can keep track of the current section, and multiply viewportHeight
by the current section. That way you can scroll section by section.
var currentSection = 0;
var totalSections = document.querySelectorAll("section").length;
$(document).on('click', '.cd-go', function(event){
event.preventDefault();
var viewportHeight = $(window).height();
currentSection++;
if (currentSection > totalSections - 1) currentSection = totalSections - 1;
$('html, body').animate({
scrollTop: viewportHeight * currentSection,
complete: function () {
$('.cd-swipe').slideDown(300);
}
}, 500);
});
.cd-go {
width: 209px;
background: rgba(0,0,0, 0.17);
height: 212px;
border-radius: 212px;
color: #fff;
position: fixed;
bottom: -106px;
text-align: center;
left: 0;
right: 0;
margin: 0 auto;
}
.w-sec {
height:100vh;
}
.w-sec:first-of-type {
background:#fff;
}
.w-sec:nth-of-type(2) {
background:#ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cd-go">
DOWN
</a><!-- scroll btn -->
<section id="section1" class="w-sec cd-section">
content
</section><!-- section 2 -->
<section id="section2" class="w-sec cd-section">
content
</section><!-- section 2 -->
<section id="section3" class="w-sec cd-section">
content
</section><!-- section 2 -->
Upvotes: 0
Reputation: 2157
Try this,
$(document).on('click', '.cd-go', function(event){
event.preventDefault();
var viewportHeight = $(document).height();
$("html, body").animate({
scrollTop: viewportHeight,
}, {
duration: 500,
complete: function () {
$('.cd-swipe').slideDown(300);
}
});
});
you are scrolling window instead of document
Upvotes: 0