jv96
jv96

Reputation: 29

jQuery scrolltop animate not animating

Here is what I have.
The clicking function works and jumps to that part of the section, but the scrolling animation isn't working.

Anything I did wrong?

    <nav class="navbar navbar-inverse navbar-fixed-top" id="my-navbar">
        <div class="container text-right">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

            </div>

<div class="collapse navbar-collapse text-left" id="navbar-collapse" >
  <ul class="nav navbar-nav">
    <li><a href="#home">Home</a></li>
    <li><a href="#skills">Skills</a></li>
    <li><a href="#feedback">Feedback</a></li>
    <li><a href="#about">About me</a></li>
    <li><a href="#contact">Contact</a></li>
  </ul>
</div>

<script>
  $("#navbar").on("click", function(e) {
    e.preventDefault();
    var section = $(this).attr("href");
    $("html, body").animate({
      scrollTop: $(section).offset().top
    }, 1500);
  });      
</script>

Upvotes: 0

Views: 57

Answers (2)

Gustaf Gun&#233;r
Gustaf Gun&#233;r

Reputation: 2267

Change the jQuery to something like this:

$(".navbar-nav a").on("click", function(e) {
    e.preventDefault();
    var section = $(this).attr("href");
    $("html, body").animate({
      scrollTop: $(section).offset().top
    }, 1500);
  });  

Your selector is wrong. You have no element with id navbar which means that your event listener isn't even firing. That's why it doesn't animate.

Upvotes: 0

Laura
Laura

Reputation: 3383

There is no element #navbar on your page, so the click event never gets fired, and the browser just behaves as usual (jumping to the anchor) - try using something like #navbar-collapse, or .nav a.

Upvotes: 1

Related Questions