strava1
strava1

Reputation: 57

on click scroll to element

Hi there I have a problem. I need scroll to element from anchor on click but I get error:

SyntaxError: missing } after property list

scrollTop: $( $(this).attr('href') )element.offset().top

/* jQuery scroll to element on click */

$(document).ready(function(){

    $('nav#site-navigation ul li').click(function(){
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 1000);
    return false;
    });

});

anchor is in WP navigation menu

Upvotes: 4

Views: 2258

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 205969

An <li> element does not have a href attribute!
Use it's child <a> element instead

$(document).ready(function(){

    $('nav#site-navigation ul li a').click(function(evt) {
      evt.preventDefault();
      $('html, body').stop().animate({
        scrollTop: $( $(this).attr('href') ).offset().top
      }, 1000);
    });

});
nav{position:fixed;top:20px;}
.page{height:100vh;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="site-navigation">
  <ul>
    <li><a href="#home">HOME</a></li>
    <li><a href="#about">ABOUT</a></li>
    <li><a href="#contact">CONTACT</a></li>
  </ul>
</nav>
<div id="home" class="page">HOME</div>
<div id="about" class="page">ABOUT</div>
<div id="contact" class="page">CONTACT</div>

Also, don't forget to use .stop() to clear the animation queue

Upvotes: 4

Related Questions