简体   繁体   中英

Bootstrap navbar collapse on scroll

I'm using bootstrap grayscale theme for my project and It has a navbar that collapses on scroll, or if I go to a link that's on the same page (#download etc.)

The problem is when I go to anchor link from some other page, than navbar doesn't collapse until I scroll.

I guess the solution is in adding the line in java script, but I really don't know what to add since I don't know java. :-(

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar").offset().top > 50) {
    $(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
    $(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});

Please, help. :) :-*

You need to run the check when the page loads as well as when the window is scrolled, you can do that without duplicating any code by putting the logic that checks the offset of the page in a function and running it from both document ready and window scroll.

$(document).ready(function() {

    // Put your offset checking in a function
    function checkOffset() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        }     
        else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    }

    // Run it when the page loads
    checkOffset();


    // Run function when scrolling
    $(window).scroll(function() {
        checkOffset();
    });
});

Edit:

I believe you could shorten this even more by replace the checkOffset function with the following:

// Put your offset checking in a function
function checkOffset() {
    $(".navbar-fixed-top").toggleClass("top-nav-collapse", $(".navbar").offset().top > 50);
}

I haven't tested this, but as long as the second parameter in toggleClass returns a boolean it'll either add or remove the class depending on the offset of the page without needing an if statement.

You should be able to do something as simple as this..

$('.navbar-collapse ul li a').click(function() {
     /* always close responsive nav after click */
     $('.navbar-toggle:visible').click();
});

Here's an example of use

It's not Java, it's JavaScript which is easily added to your html page using script tags.

You can also use :

 $(document).ready(function() {
        function checkOffset() {
            $(".navbar").removeClass("show");
        }
        // Run function when scrolling
        $(window).scroll(function() {
            checkOffset();
        });
        // Run function on Clicking
        $(window).click(function() {
            checkOffset();
        });
    });

This will help with navbar collapse on mobile devices .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM