Quantcast
Channel: Cheesetoast » transition
Viewing all articles
Browse latest Browse all 2

Fixed top menu that fades and shrinks when scrolled

$
0
0

This top menu bar will stick to the top of the page, but when the user scrolls down the menu will shrink slightly and become semi-transparent. I used javascript to add a CSS class with a transition effect applied.

See the Pen Shrink & Fading – Fixed Menu Bar by Graham Clark (@Cheesetoast) on CodePen.

HTML

We start with the html5 nav element with a fairly standard horizontal unordered list for the menu:

<nav>
  <ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
  </ul>
</nav>

CSS

nav {
  background: black;
  color: white;
  transition: opacity 1s ease;
  opacity: 1;

  height: 80px;
  line-height: 80px;
  width: 100%;

  position: fixed;
  top: 0;
  left: 0;
}
nav a {
  color: white;
  text-decoration: none;
}

nav:hover { opacity: 1 }

First I start by styling the visuals. The opacity is set to 1 with a CSS3 transition so that the changes are made smoothly.

The line-height is the same as the height of the nav bar, so that the text is vertically centered.

The position of the nav is fixed at the top left with a width of 100%.

Finally, I added a hover option that sets opacity to 1 again so the user can view the menu more clearly.

Next I’ll add the class that javascript calls when the user scrolls:

.scrolled {
  opacity: 0.7;
  height: 50px;
  line-height: 50px;
}

JAVASCRIPT (JQUERY)

$(window).scroll(function(){

  var scroll = $(window).scrollTop();

  if (scroll > 0 ) {
    $('nav').addClass('scrolled');
  }

  if (scroll <= 0 ) {
    $('nav').removeClass('scrolled');
 }

});

(Don’t forget to include jQuery if you’re using this code)

This code is pretty straight forward. As the user scrolls the function is called. The variable ‘scroll’ basically measures the amount of space from the top of the page to the top of the window, i.e. before you start scrolling the distance is 0.

Depending on the scroll amount, the javascript adds / removes the ‘scrolled’ class.

The CSS3 transitions will degrade gracefully and a lack of javascript support shouldn’t make anyone cry either. Hope this code has been of interest!

The post Fixed top menu that fades and shrinks when scrolled appeared first on Cheesetoast.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images