简体   繁体   中英

I have a navigation menu and I want that it's list items, on click, go to a specific div

sorry if this question has already been answered. I've tried searching for other answers but still couldn't solve it. I'm new to jQuery..

So, I have a navigation menu and I want that it's list items, on click, go to a specific div.

Here's my code:

HTML

<div class="overlay" id="nav-overlay">
  <nav class="overlay-menu">
    <ul>
      <li ><a class="nav-link" href="#" data-target="intro">Home</a></li>
      <li><a class="nav-link" href="#" data-target="about-section">About</a></li>
      <li><a class="nav-link" href="#" data-target="hero-section-1">Projects</a></li>
      <li><a class="nav-link" href="#" data-target="contact-section">Contact</a></li>
    </ul>
  </nav>
</div>

And Jquery:

// Scroll to div

$(document).on('click','.nav-link', function(event) {
    event.preventDefault();
    var target = this.getAttribute('data-target');
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);
});

When I click on the links nothing happens, and in my console i get this error:

Uncaught TypeError: Cannot read property 'top' of undefined

Any help will be appreciated :)

you need to pre-fix the target with its selector:-

// if the target is a class
$('.' + target).offset().top

// if the target is a id
$('#' + target).offset().top

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM