0

I am trying smooth scroll spy for non-body element and I can't succeed it work properly, what I am missing? It is working for the body but not working for sections or divs etc. The second click to the nav element has some wrong behaviour.

I would like to use the smooth scroll for other elements then body.

I am trying to solve a few days but couldn'T find any solution.

<section>
<div id="nav" class="active-spy target-cstm">
  <ul class="nav">
    <li>
      <a href="#first">1st</a>
    </li>
    <li>
      <a href="#second">2nd</a>
    </li>
    <li>
      <a href="#third">3rd</a>
    </li>
    <li>
      <a href="#fourth">4th</a>
    </li>
  </ul>
</div>
<div id="first">
  first div
</div>
<div id="second">
  second div
</div>
<div id="third">
  third div
</div>
<div id="fourth">
  fourth div
</div>
</section>
#nav {
  position: fixed;
  right: 1em;
  min-width: 10em;
}

.active {
  background-color: #f9f;
}

div:not(#nav) {
  height: 500px;
}
section {height:200px; position:relative; overflow-y:scroll; background:grey;}
$("section").scrollspy({
  target: ".target-cstm"
});

$(document).on('click', 'a', function(event) {
  $('section').animate({
    scrollTop: $($.attr(this, 'href')).offset().top
  }, {
    duration: 300,
    start: function() {
      $("#nav").removeClass("active-spy");
    },
    complete: function() {
      $("#nav").addClass("active-spy");
      $(".active").removeClass("active");
      $(event.target.parentNode).addClass("active");
    }
  });
});

You can check here: https://jsfiddle.net/digitayfun/vcq2hkfu/5/

digita
  • 11
  • 1
  • I think this link will help you - https://stackoverflow.com/questions/30348314/how-to-use-scrollspy-without-using-bootstrap – Rashed Hasan Jan 09 '20 at 12:56
  • @RashedHasan thank you, I need smooth-scroll so I will play around for how I can get it with that example. If I don't add smooth scroll it was also working with me. – digita Jan 09 '20 at 13:04
  • Bro, I tried unfortunately also result is the same you can check here https://jsfiddle.net/digitayfun/1cyw8fph/13/ I am doing something wrong with the selector. I try to make it work in container, not in the body. @RashedHasan – digita Jan 09 '20 at 13:25

0 Answers0