Scroll To Element
HTML
<a class="js-scroll-to-element" href="#section-north-america">North America</a>
<a class="js-scroll-to-element" href="#section-europe">Europe</a>
<a class="js-scroll-to-element" href="#section-asia">Asia</a>
<a class="js-scroll-to-element" href="#section-australia">Australia</a>
<div id="section-north-america">Welcome to North America!</div>
<div id="section-europe">Welcome to Europe!</div>
<div id="section-asia">Welcome to Asia!</div>
<div id="section-australia">Welcome to Australia!</div>
CSS
* {
text-align: center;
}
a {
display:inline-block;
margin-top:20px;
width:20%;
}
div {
margin-top:300px;
}
div:last-child {
margin-bottom:900px;
}
JavaScript
(function($) {
////////////////////////////////////////////////////////
///////////////// SCROLL TO ELEMENT ////////////////////
////////////////////////////////////////////////////////
var $htmlBody = $( 'html, body' ),
$jsScroll = $('.js-scroll-to-element'),
hash = window.location.hash,
speed = 600, // millesconds it takes to reach the item
stopHere = -30, // pixels from element when it stops
target,
withHash;
function animateToElement() {
console.log('withHash' + withHash);
// scroll to id that matches href and animate
$htmlBody.animate({
scrollTop: $(withHash).offset().top + stopHere
}, speed);
}
$(window).load(function() {
// if address bar has hash scroll to element
if (hash.length) {
// update hash
withHash = hash;
// initiate scroll to function
animateToElement();
}
});
function scrollToElement() {
// grab href
target = $(this).attr('href');
// update hash
withHash = target;
// initiate scroll to function
animateToElement();
}
$jsScroll.on('click', scrollToElement);
})(jQuery);