I'm trying to animate the scroll when the same button is clicked but on different scroll areas like:
- if the scroll is 0 or less than 300 px and the button is clicked, to animate the scroll to the specified element.
- if scrolling more than 300px, and the button is clicked, to animate the scroll to the top of the page.
But so far the first state is working but the second one, if the button is clicked will scroll to the top of the second section and not the top of the page (body).
$(window).scroll(function() {
if ($(this).scrollTop() > 300) {
// if scrolling more than 300px add classes active and up
$('#scroll-button').addClass('active up').removeClass('down');
} else {
// is no scroll or less than 300px, remove class active and add class down
$('#scroll-button').removeClass('active up').addClass('down');
}
});
// is no scroll or less than 300px and #scroll-button.down is clicked, animate scrolling to the next element
$('.down').on('click', function() {
$('html,body').animate({
scrollTop: $("#second").offset().top
},
600);
return false;
});
// if scrolling more than 300px and #scroll-button.up button is clicked, animate scroll to the top of the page
$('.up').on('click', function() {
$('html, body').animate({
scrollTop: 0
}, 600);
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first" class="section"><button id="scroll-button" class="down" type="button">Click Me!</button></div>
<div id="second" class="section">Hi</div>
jsfiddle: http://jsfiddle.net/uky5fs1d/2/