Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap offset scrollspy not working

The navbar works as well as the smooth scroll, but I can not change the offset. My nav is 86px but no matter how many px I change it still goes to the same place.

$(document).ready(function () {
     $('body').scrollspy({target: ".navbar", offset: 86});   
     $("#myNavbar a").on('click', function(event) {
        if (this.hash !== "") {
            event.preventDefault();
            var hash = this.hash;
            $('html, body').animate({
                scrollTop: $(hash).offset().top
                }, 800, function(){
                window.location.hash = hash;
            });
         }
     });
});

I added the info directly to the body tag and still no change. I know that jquery is working as it does scroll smooth and the collapse nav works as well.

<body data-spy="scroll" data-target=".navbar" data-offset="86">
like image 254
JonW Avatar asked Jun 12 '16 02:06

JonW


People also ask

What is offset in scrollspy?

Offset is a Bootstrap Scrollspy property wherein the user can specify the pixels to offset from top when calculating the position of scroll.

How does Bootstrap Scrollspy work?

The Bootstrap scrollspy is a navigation mechanism that automatically highlights the nav links based on the scroll position to indicate the visitor where they are currently on the page.

How do you make Scrollspy?

Scrollspy is created by using attribute data-bs-spy=” scroll” and data-bs-target attribute on the body tag to make it scrollable and if you want to apply these attributes on a div then add data-offset attribute and set overflow to auto.

What is the purpose of using Scrollspy?

The Scrollspy plugin is used to automatically update links in a navigation list based on scroll position.


2 Answers

I don't think offset does what you think it does. I Doesn't determine the 'scroll-to' position. You'll have to do that with padding.

Offset in this context means the distance between the top of the screen and the section you're scrolling to. In other words: all it does is determine at which moment the navbar > a tag changes to an active state.

like image 195
Wietse de Vries Avatar answered Oct 14 '22 23:10

Wietse de Vries


Yes, offset is only there to determine when your nav link is highlighted. Not to position your screen when clicking on the link. I.e. the scrolling part is up to you. You can use a little JS to do that like this:

var offset = 80;

    $('.navbar li a').click(function(event) {
        event.preventDefault();
        $($(this).attr('href'))[0].scrollIntoView();
        scrollBy(0, -offset);
    });
like image 33
Josh Avatar answered Oct 14 '22 21:10

Josh