A basic jQuery scroller
, by
Aurélien Aries
I was looking for a nice jQuery scroller plugin for a client website and though I should write my own. I end up with a little (really basic) jQuery code.
Considering the followings CSS & HTML :
body {
width: 600px;
margin: 0 auto;
text-align: center;
}
section { min-height: 1000px; }
h1 { font-size: 96px;}
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #999;
}
a {
color: #fff;
font-size: 20px;
margin:0 30px;
}
<!-- NAVIGATION -->
<nav>
<a href="#1">1</a>
<a href="#2">2</a>
<a href="#3">3</a>
<a href="#4">4</a>
</nav>
<!-- CONTENT -->
<section id="1">
<h1>Title 1</h1>
<p>paragraph 1</p>
</section>
<section id="2">
<h1>Title 2</h1>
<p>paragraph 2</p>
</section>
<section id="3">
<h1>Title 3</h1>
<p>paragraph 3</p>
</section>
<section id="4">
<h1>Title 4</h1>
<p>paragraph 3</p>
</section>
Then add the following scripts, just before the </body>
tag :
$('a[href^="#"]').on('click', function(e){
e.preventDefault();
var anchor = $(this).attr('href'),
sectionPosition = $(anchor).offset().top;
$('html, body').animate({
scrollTop: sectionPosition - 100
});
});
The code is really simple, and some part can be improved, but this is a really easy and quick way to set up your own scroll without installing a plugin.