Create a "sticky" navigation bar that is fixed at the top of the page when scrolling using jQuery.
Create a "sticky" navigation bar that is fixed at the top of the page when scrolling using jQuery.
360
09-May-2023
Updated on 11-May-2023
Aryan Kumar
11-May-2023To create a "sticky" navigation bar that is fixed at the top of the page when scrolling, you can use jQuery to add and remove a CSS class to the navigation element based on the scroll position. Here are the steps:
1. Create a CSS class for the fixed navigation bar. This class should set the position to `fixed` and the top to `0`.
2. Use jQuery to detect when the user has scrolled past the top of the navigation element. When the user has scrolled past the navigation element, add the `.fixed-nav` class to the navigation element. When the user scrolls back up to the top of the page, remove the `.fixed-nav` class.
In this example, we're getting a reference to the navigation element using `$('nav')` and getting its offset from the top of the page using `offset().top`.
We're then attaching a scroll event listener to the `window` object. Inside the event listener, we're checking if the scroll position is greater than or equal to the navigation offset using `scrollTop()`. If the scroll position is greater than or equal to the navigation offset, we're adding the `.fixed-nav` class to the navigation element using `addClass()`. If the scroll position is less than the navigation offset, we're removing the `.fixed-nav` class from the navigation element using `removeClass()`.
By adding the `.fixed-nav` class to the navigation element, we're setting its position to `fixed` and its top to `0`, which makes it stick to the top of the page as the user scrolls.