When you first land on a page, it is possible to have the page scroll down to some remote div further down the page, using a little bit of jQuery. For example, if the remote div is called “remoteDiv”, this jQuery will automatically scroll down to the div when the page loads:
$(".remoteDiv").ready(function() { $('html,body').animate({ scrollTop: $(".remoteDiv").offset().top}, 'slow'); });
What this jQuery does is it selects the remoteDiv, and when the remoteDiv is loaded (.ready( )
), it selects the page body and animates down to the remoteDiv slowly.
Once the user has been scrolled down to the remoteDiv, a similar jQuery code snippet can be used to scroll back up to the top “targetDiv”. This is based on clicking the remoteDiv. For example:
$(".remoteDiv").click(function() { $('html,body').animate({ scrollTop: $(".targetDiv").offset().top}, 'slow'); });
The two differences in this jQuery snippet are 1. it is triggered by clicking the remoteDiv with a click event and 2. it scrolls up to targetDiv.
Here is the complete HTML code:
<div class="targetDiv"> <h2>This is the target div...</h2> </div> <div class="remoteDiv" id='rd'> <h2>Click this text! <br>This is the div that is way down at the bottom of the page..</h2> </div>
Here is the complete CSS:
body { background: #333; padding: 10px; } h2 { padding: 10px; } .targetDiv { width: 100%; height: 1500px; background: #59A3C8; } .remoteDiv { width: 100%; height: 1000px; background: #ccc; }
And here is the complete jQuery code:
$(".remoteDiv").ready(function() { $('html,body').animate({ scrollTop: $(".remoteDiv").offset().top}, 'slow'); }); $(".remoteDiv").click(function() { $('html,body').animate({ scrollTop: $(".targetDiv").offset().top}, 'slow'); });
I have a demo of this code on codepen:
See the Pen scroll to div by Chris Nielsen (@Chris_Nielsen) on CodePen.0
For more information about each of these jQuery functions see:
.ready()
.click()
.animate()
scrollTop
.offset()