Codementor Events

Creating your own affix with CSS & jQuery

Published Oct 06, 2017Last updated Apr 04, 2018
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
post commentsBe the first to share your opinion
sheriffderek
4 years ago

You can use ‘position: sticky’ now (make sure to add the top property). Also - just regular core JavaScript can do all of this just fine also.

Gee
6 years ago

Hi thanks, I actually want to do an Affix but without the trouble of using the overhyped Bootstrap. Now my idea was to have this fixed menu appear after the first screen. Shall I just mod to top:100% in the .affix ?

LAU TIAM KOK
6 years ago

Sorry just saw your message. What do you mean top:100%? Do you have any working code for what you are trying to do? You don’t need Bootstrap for an Affix. Yes, it is overhyped :-)

Show more replies