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 so when its clicked, it scrolls to specific div.
$(".next").click(function() { $('html,body').animate({ scrollTop: $(".p2").offset().top}, 'slow'); });
body{ margin: 0; height: 100%; } .p1{ height: 100vh; width: 70%; background-color: #2196F3; } .p2{ height: 100vh; width: 70%; background-color: #E91E63; } .p3{ height: 100vh; width: 70%; background-color: #01579B; } .admin{ background-color: #B71C1C; height: 100vh; position: fixed; right: 0%; top: 0%; width: 30%; float: left; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="p1"> </div> <div class="p2"> </div> <div class="p3"> </div> <div class="admin"> <button class="next">NEXT</button> </div>
To set the scroll position of an element (the other div ), you set the element's scrollTop and scrollLeft values (which are in pixels). If you want two divs to scroll in near-unison, for instance, you'd assign the source div's scrollTop and scrollLeft to the target div .
To scroll the page with JavaScript, its DOM must be fully built. For instance, if we try to scroll the page with a script in <head> , it won't work. Regular elements can be scrolled by changing scrollTop/scrollLeft . We can do the same for the page using document.
Use the scroll() Function to Scroll to an Element in JavaScript. The element interface's scroll() function scrolls to a specific set of coordinates within a given element. This is suitable for Chrome and Firefox and not for the rest. Copy window.
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; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="p p1 active"></div> <div class="p p2"></div> <div class="p p3"></div> <div class="admin"> <button class="next">NEXT</button> </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With