Search code examples
jqueryhtmljquery-pluginsnavigationsticky

HTML -- How can I "stick" my navbar after reaching a specific section on page?


I thought of 2 different methods to approaching this, but I need assistance.

  1. Scroll to section and then stick.
  2. Hide element while scrolling, then unhide element once you have reached point on page.

How can I do this?

I'm using stickyjs currently.

But I don't see a feature for doing what I asked.


Solution

  • demo - http://jsfiddle.net/m6q6j8xL/3/

    this is custom js

    in this demo the header changes to green(fixed) and when you reach to blue div changes back to normal and when u are out from the blue div it changes back to fixed

    padding is added to div so that it doesn't effect window scroll when changed to fixed

    var stickyNavTop = $('.header').offset().top;
    
    function scrolling() {
        doc = $(document).height()
        hidingtop = $('.hiding').offset().top;
        hidingbottom = $('.hiding').position().top + $('.hiding').outerHeight(true) // finding the outer height
        if ($(window).scrollTop() > hidingtop && $(window).scrollTop() < hidingbottom) {
            $('.header').removeClass('sticky');
            $('.container').css('padding-top', '0');
        }
    }
    
    var stickyNav = function () {
        var scrollTop = $(window).scrollTop();
    
        if (scrollTop > stickyNavTop) {
            $('.header').addClass('sticky');
            $('.container').css('padding-top', '100px');
        } else {
            $('.header').removeClass('sticky');
            $('.container').css('padding-top', '0');
        }
    };
    
    stickyNav();
    
    $(window).scroll(function () {
        stickyNav();
        scrolling()
    });