Smooth link anchor scrolling

Asked

Viewed 4,920 times

3

The following JS aims to promote smooth scrolling when we click on anchors on a website one-page. There is how to restrict its performance only with resolutions higher than 760px?

$(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 () {
                    $('html, body').animate({scrollTop: targetOffset}, 300);
                    return false;
                });
            }
        }
    });
});
  • Sorry ignorance, when you say resolution is referring to window.screen.availHeight window.screen.availWidth ?

1 answer

4


Just change this snippet of your code:

$(this).click(function () {
   if($(window).width() > 760){
      $('html, body').animate({scrollTop: targetOffset}, 300);
      return false;
   }
});

Example I had to put the code in Jsfiddle because it doesn’t work as it should in snippet Stackoverflow. To reproduce, simply decrease the result for a size < 200.

  • Thanks for the tip Renan. I was not knowing where to apply this rule pro code only make up to 760px.

Browser other questions tagged

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