Problem in smoothing scroll on anchor links

Asked

Viewed 245 times

0

Beginner in Jquery, but I used this script I found to give the smoothing effect in the scroll to the link "anchored":

$(document).ready(function () {
    function filterPath(string) {
        return string
            .replace(/^\//, '')
            .replace(/(index|default).[a-zA-Z]{3,4}$/, '')
            .replace(/\/$/, '');
    }
    $('a[href*=#]').each(function () {
        if (filterPath(location.pathname) == filterPath(this.pathname)
                && location.hostname == this.hostname
                && this.hash.replace(/#/, '')) {
            var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']');
            var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
            if ($target) {
                var targetOffset = $target.offset().top;
                $(this).click(function () {
                    if($(window).width() > 760){
                        $('html, body').animate({scrollTop: targetOffset}, 250);
                        return false;
                    }
                });
            }
        }
    });
});

HTML

    <nav id="menu">
       <ul>
        <div class="marcadagua"> <a href="#"> <img src="logo_menu.png"> </a></div>
        <li><a href="#qs">Quem somos</a></li>
        <li><a href="#parceiros">Parceiros</a></li>
       </ul>
      </nav>
--
<div class="divancora"> <a name="qs"></a> </div>
<div class="divancora"> <a name="parceiros"></a> </div>

It occurs that it somehow does not lead to the exact point intended. It always gives a difference in height to the point it should go. It is not a fixed difference.

I’d like to know why.

  • Give a difference down or up? probably it gets lower than you want, try to add targetOffset - 100

  • It’s actually a difference up.

  • Try to do instead of -100 use + 100

  • It can be some padding or margin in CSS, it can provide an example in fiddle or stacksnippet?

  • I had put a padding yes because the menu at the top followed the scrolling of the page so as to overlap the link, however that was not the reason. Apparently it was something in js that didn’t work properly anyway. grateful.

1 answer

1


Try this script on.

Its use is simpler and you can see its working here.

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
  • Thank you Erlon!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.