3

I wanted my navigation to behave like a "sticky nav" and rather than use a plugin, so I tried to just come up with a solution myself.

It seemed like the most appropriate thing to do is just change all the css values with jquery in a conditional statement.

Here was my solution to this problem:

$(window).scroll(function() {
    if($(document).scrollTop() > 50)
    {
        $('.site-header').css("height", "48px");
        $('.site-title a').css("background-size", "45px 45px");
        $('.genesis-nav-menu > li').css("line-height", "50px");
        $('.genesis-nav-menu .sub-menu').css("top", "0").css("margin-top", "48px");
    }
    else
    {
        $('.site-header').css("height", "100px");
        $('.site-title a').css("background-size", "101px 101px");
        $('.genesis-nav-menu > li').css("line-height", "100px");
        $('.genesis-nav-menu .sub-menu').css("top", "100").css("margin-top", "100px");
    }
});

The margin-top funny business is to correctly align the sub-menus. I'm sure there's a better way to do that. However, my question is: is there a more performant way to do this?

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
Seth Johnson
  • 135
  • 1
  • 1
  • 11

1 Answers1

0

There are too many things happening for every pixel that the Browser scrolls. Here are some good practices about the scroll event: jQuery resize(), scroll(): good practice to use variables?

I would do something like this:

Markup:

<div id="menu">
  <ul>
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
    <li>Careers</li>
    <li>More</li>
  </ul>
</div>

JS:

(function($) {
  $(document).ready(function() {
    var 
    $menu = $('#menu'),
    $clone = $menu.clone(true),
    $window = $(window),
    top = $menu.offset().top,
    topDown = top + $menu.height(),
    currentScroll = 0;

    $clone.addClass('fixed');
    $menu.before($clone);

    $window.scroll(function() {
      currentScroll = $window.scrollTop();

      if(currentScroll > topDown) {
        $menu.addClass('invisible');
        $clone.addClass('visible');
      } else {
        $menu.removeClass('invisible');
        $clone.removeClass('visible');
      }
    });
  });
})(jQuery);

CSS:

#menu { background: #e55; }
#menu ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
#menu li {
  display: inline-block;
  padding: 12px;
}
.fixed {
  position: fixed;
  top: 0;
  left: 1em;
  right: 1em;
  z-index: 99;
  opacity: 0;
}
.visible {
  opacity: 1;
  -webkit-transition: opacity .5s ease-in;
  -moz-transition: opacity .5s ease-in;
  transition: opacity .5s ease-in;
}
.invisible { visibility: hidden; }
Dave
  • 3
  • 1
  • 3
istos
  • 2,654
  • 1
  • 17
  • 19