Firefog Firefog - 1 month ago 11
CSS Question

How to make a navigation sticky when it reached to another top nav

I have two navigation one is on the top and another is in content. I try to make the second sub menu as sticky when it reached to the top menu not the very top offset of browser. But i failed to make it sticky when it scrolled to top. Also how can I add class on on menu item when active 'href' scrolling.

JSfiddle Here

JS Code

$(document).ready(function() {
var $filter = $('.denpen-menu');
var $filterSpacer = $('<div />', {
"class": "filter-drop-spacer",
"height": $filter.outerHeight()
});

if ($filter.size())
{
$(window).scroll(function ()
{
if (!$filter.hasClass('navbar-fixed') && $(window).scrollTop() > $filter.offset().top)
{
$filter.before($filterSpacer);
$filter.addClass("navbar-fixed");
}
else if ($filter.hasClass('navbar-fixed') && $(window).scrollTop() < $filterSpacer.offset().top)
{
$filter.removeClass("navbar-fixed");
$filterSpacer.remove();
}
});
}
});

Answer

First we should fetch the starting position of our subNavand store it as "startingPoint"

var startingPoint = $('.stuckMenu').offset().top - 48;

Notice the - 48 part, that's about the height of our main navigation, and a bit less just so it feels better when they touch.

The key part of the logic is this part here:

if (!subNav.hasClass('navbar-fixed') && $(window).scrollTop() > startingPoint)
{     
    $filter.addClass("navbar-fixed");
}
else if(subNav.hasClass('navbar-fixed') && $(window).scrollTop() < startingPoint)
{      
    $filter.removeClass("navbar-fixed");
}

Where we ask:

  1. Is our subNav sticky yet? Is the top of the window touching it currently?

    Ok its not sticky yet but the window touched it, make it sticky - fixed.

  2. Ok so our subNav is sticky, is the top of the window above the original position of our subNav?

    It is above? Ok I do not want it to be sticky any more, so we'll just remove the class.

Check out the example here