The Affix plugin allows an element to be attached (locked) to a specific region on the page. This is commonly used with navigation menus or social icon buttons to make them “stick” in a set location while scrolling up and down the page.
Depending on the scroll position, the plugin toggles this behavior on and off (changing the CSS positionvalue from static to fixed).
Example 1) A fixed navbar:
---- SCROLL MUKAVU ----
Example 2) An attached sidebar:
---- SCROLL MUKAVU ----
With Affix, the menu remains visible and locked in place when we navigate up and down the page.
How To Create an Affixed Navigation Menu
The example below explains how to make a horizontal attached navigation menu.
Example
The example below explains how to make a vertical attached navigation menu.
Example
Example explained
Add data-spy=”affix” to the element you want to affix.
To compute the scroll position, optionally add the data-offset-top|bottom attribute.
How it works
The affix plugin can switch between three classes: .affix, .affix-top, and .affix-bottom. Each class represents a specific state. With the exception of position:fixed on the .affix class, CSS properties must be added to handle actual positions.
The plugin adds the .affix-top or .affix-bottom classes to denote whether the element is at the top or bottom. CSS positioning is not required at this time.
Scrolling past the affixed element initiates the affixing process, in which the plugin replaces the .affix-top or .affix-bottomclasses with the .affix class. At this point, you must use the CSS topor bottomproperty to place the attached element on the page.
If a bottom offset is specified, scrolling past it replaces the .affix class with .affix-bottom. Because offsets are optional, you must first apply the relevant CSS. In this scenario, use position:absolute when necessary.
In the first example above, the Affix plugin applies the .affix class (position:fixed) to the <nav> element after scrolling 197 pixels from the top. If you open the sample, you will notice that we have added the CSS topattribute with a value of 0 to the .affix class. This ensures that the navbar remains at the top of the page even after we’ve scrolled 197 pixels.
Scrollspy & Affix
Using the Affix plugin alongside the Scrollspy plugin: