1

I'm having some difficulty getting my webpage to utilize a smooth scroll. I have a navbar at the top of the page with 4 options on it. Each option corresponds to a section further down on the page. I would like to be able to click on those items in the navbar and have a smooth scroll down to its corresponding section. I've tried utilizing both the below questions (among several other online resources!!), but I can't seem to get it work. Any assistance offered would be much appreciated! Summarized version of code is below

jQuery scroll to element

Smooth scroll anchor jquery

HTML

<ul id="navbar">
            <li><a class="about" href="#about">ABOUT</a></li>
            <li><a class="shop" href="#shop">SHOP</a></li>
            <li><a class= "featured" href="#featured">FEATURED</a></li>
            <li><a class="updates" href="#updates">UPDATES</a></li>
        </ul>

<div id="handcrafted"></div>
<div id="shop"></div>
<div id="featured"></div>
<div id="updates"></div>

JS

$('.about').click( function() {
     $('html, body').animate({
          scrollTop: $('#about').offset().top
     }, 400);
});


$('.shop').click( function() {
     $('html, body').animate({
          scrollTop: $('#shop').offset().top
     }, 400);
});



$('.featured').click( function() {
     $('html, body').animate({
          scrollTop: $('#featured').offset().top
     }, 400);
});



$('.updates').click( function() {
     $('html, body').animate({
          scrollTop: $('#updates').offset().top
     }, 400);
});
Dudley
  • 28
  • 3

1 Answers1

0

<div id="handcrafted"></div> should be <div id="about"></div>

And if you're dealing with <a>, I suggest to add e.preventDefault() all the time unless you want a pure <a>.

$('a').click( function(e) {
     e.preventDefault()
     $('html').animate({
          scrollTop: $($(this).attr('href')).offset().top
     }, 400);
});
div{
  height: 50vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="navbar">
            <li><a class="about" href="#about">ABOUT</a></li>
            <li><a class="shop" href="#shop">SHOP</a></li>
            <li><a class= "featured" href="#featured">FEATURED</a></li>
            <li><a class="updates" href="#updates">UPDATES</a></li>
        </ul>

<div id="about">ABOUT</div>
<div id="shop">SHOP</div>
<div id="featured">FEATURED</div>
<div id="updates">UPDATES</div>
Hikarunomemory
  • 3,902
  • 2
  • 7
  • 19