JS tips: Creating your own affix with CSS & jQuery

Published Oct 06, 2017Last updated Dec 13, 2017
JS tips: Creating your own affix with CSS & jQuery

Affix navigations are quite common these days. They are just HTML elements that become affixed (locked) at a specific area on the page while scrolling up and down the page. There are JavaScript plugins that help you to do that, such as Bootstrap Affix Plugin.

The challenge

However, not all these plugins suit you right out of the box. You may need to do some painful customisations, or they just don't work at all for you design.

A solution

Creating your own affix navigation is easier than you think. You can just use CSS & jQuery with just a few lines of code to help you to achieve that.

  1. Create a normal navigation with either Bootstrap or Foundation (I prefer Foundation):
<div class="row navbar">
  <ul class="menu">
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
    <li><a href="#">Four</a></li>
  </ul>
</div>
  1. Create a .affix class in your CSS with position: fixed and set display: none:
.affix {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9999;
    display: none;
}
  1. Use jQuery to clone .navbar to .affix and set display: block to .affix on the scroll event:
var target = $('.navbar')
target.after('<div class="affix" id="affix"></div>')

var affix = $('.affix')
affix.append(target.clone(true))

// Show affix on scroll.
var element = document.getElementById('affix')
if (element !== null) {
  var position = target.position()
  window.addEventListener('scroll', function () {
    var height = $(window).scrollTop()
    if (height > position.top) {
      target.css('visibility', 'hidden')
      affix.css('display', 'block')
    } else {
      affix.css('display', 'none')
      target.css('visibility', 'visible')
    }
  })
}

Suggestions

Let me know what you think and what would be your solutions. Anything suggestions, please leave a comment below. Hope this helps. You can download and see how I use it on one of my projects in GitHub.

Discover and read more posts from LAU TIAM KOK
get started
Enjoy this post?

Leave a like and comment for LAU