Site icon N77 Design | NickClaeboe.com

Smooth Scrolling CSS jQuery Trick Hack Code Tutorial

While coding websites for several different clients, I’ve repeatedly had the need to a smooth scroll anchor function. Through several hours of searches and digging, I found something, that was actually in a comment somewhere, that executed the scroll function perfectly. Just a few lines of code and viola! It’s very light weight and uses a bit of css and jquery.

Place the code below right before the closing head tag “</head>”

<!-- SMOOTH SCROLL PLACE IN HEAD -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
<!-- End of SMOOTH SCROLL -->

And now with the following code, place it just after the opening <body> tag.

<body>
tag ==> <div name="top"> </div>
<p>somethings</p>
ANCHOR LINK ==>    <a href="#top"> Go to top </a>

Try it out for yourself and enjoy the results.

Exit mobile version