When clicking on an item

Hi, I have a problem. I need to scroll an element from the binding on click, but I get an 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 the WP navigation menu.

+4
source share
1 answer

The item <li>has no attribute href!
Use a child instead<a>

$(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>
Run code

Also, be sure to use the .stop()animation queue to clear the queue.

+3
source

Source: https://habr.com/ru/post/1652681/


All Articles