Smooth scrolling to snap offset pixels except for one specific anchor?

I have UL nav, I have this smooth jQuery scroll works:

$(document).ready(function () { $(document).on("scroll", onScroll); //smoothscroll $('a[href^="#"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('a').each(function () { $('.nav').removeClass('active'); }) $('.nav').addClass('active'); var target = this.hash, menu = target; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top-59 }, 500, 'swing', function () { window.location.hash = target; $(document).on("scroll", onScroll); }); }); }); 

it goes at -59 pixels, and this is what I need for all but one anchor, is there a way to add a line of code that says “except for class X” or something else? JQuery newbie here;)

Any help would be great, thanks.

+6
source share
1 answer

In the click event, you have access to the navigation element that you clicked on (this) and the target you are scrolling for ($ target). You can look at any of them to determine that you need to compensate for some amount other than -59.

If you have very few cases, you need to have a different offset, you can do this:

 var offset = -59; if ($(this).attr(href)=="#something") offset=-100; //or whatever special offset you need 

And change this line:

 'scrollTop': $target.offset().top-59 

:

 'scrollTop': $target.offset().top+offset 

If you want a more universal solution and access html, you can put the data attribute in either the <a> or the target element, for example

 <a href="#something" data-scroll-offset=-100></a> 

And then, similar to the first method:

 var offset=-59; if ($(this).attr("data-scroll-offset")!==null) offset=$(this).attr("data-scroll-offset"); 

If it were on the target, it would be $ target instead of $ (this)


If you want to completely exclude a specific anchor, you can remove it from the anchor selector. Instead of this

 $('a[href^="#"]') 

Exclude only a specific anchor, for example:

 $('a[href^="#"]:not([href="#somethingBad"])') 

or exclude any anchors with a specific class, for example:

 $('a[href^="#"]:not(.excludeMe)') 
+1
source

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


All Articles