Sticking An Element To The Top Of The Browser After Scroll

You can stick an element to the head of the browser after a user has scrolled past it with either pure CSS or jQuery with the help of Waypoints and Sticky Elements.

CSS

You can actually do this with a simple CSS property position:sticky

You would apply some CSS to an element that you want to stick…..

Hello Sticky

This sticky element above is given an aptly name class .sticky-thing with some CSS properties defined

.sticky-thing {
	position: -webkit-sticky;
	position: sticky;
	top: 0;
	z-index: 9999;
}

Select a top/bottom/right/left property for the position and a value for the offset – to get to the edge use 0. I have added a z-index to trump other elements. The webkit prefix is also needed for Chrome/Safari.

Can I Use

  Can I Use css-sticky? Data on support for the css-sticky feature across the major browsers from caniuse.com.

The sticky element will stick to the confinement of its parent container,  this could be a limitation for you, or you may need some older browser support, if so use the jQuery solution

jQuery Way(point)

Grab both minified JS file from the latest WayPoint release:

  • jquery.waypoints.min.js
  • sticky.min.js

Enqueue the Scripts

Enqueue the scripts along with a firing script it is important that these are loaded in the correct order. The waypoints script is dependent on jquery, the sticky script is dependent on waypoints and the init script is dependent on sticky.

So in the example above I want the .header-row element to stick to the head.

The direction parameter by default is set to up, to swap the scroll set to down.

Add Some CSS

.stuck {
	position:fixed;
	top:0;
	width: 100%;
	z-index: 999;
  }

Finally, you need to add some CSS for the .stuck class which gets attached to the stuck element – adjust it as required.

ref

Leave a Comment