I have a list based navigation at the top of my site, it's a one page site so the a hrefs are anchors to sections on the page. I've used this code: jQuery smooth scroll positioning doesn't work
Navigation:
<nav>
<ul class="navigation">
<li class="navigation"><a class="scroll" href="#about-me">about me</a>
</li>
<li class="navigation"><a class="scroll" href="#my-skills" >my skills</a>
</li>
<li class="navigation"><a class="scroll" href="#portfolio">portfolio</a>
</li>
<li class="navigation"><a class="scroll" href="#contact">contact</a>
</li>
</ul>
</nav>
Section/div:
<section id="contact"> <!---->
<div class="panel" id="contact">
<h2>Contact</h2>
</div>
</section> <!---->
Javascript used:
<script type="text/javascript">
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': parseInt($target.offset().top,10);
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
</script>
The anchor works and it jumps to the section, but with no scrolling?
There are few problems in your code:
- You haven't closed your
li
s properly- You have same
id
s forsection
anddiv
which is invalid
<section id="contact"> <!---->
<div class="panel" id="contact">
So correcting the above mistakes I would like to add one more change in your JS which is:
- No need to add
parseInt
toscrollTop
. You can directly go with theoffset().top
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top //no need of parseInt here
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});