Home >Web Front-end >CSS Tutorial >How do I create a sticky navigation bar that attaches to the top upon scrolling?

How do I create a sticky navigation bar that attaches to the top upon scrolling?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 13:40:02646browse

How do I create a sticky navigation bar that attaches to the top upon scrolling?

Creating a Sticky Navigation Bar that Attaches to the Top upon Scrolling

Problem:

Design a navigation bar positioned at the bottom of the visible page initially. When a user scrolls down, the navigation bar ascends until it fixes at the top of the page.

Solution:

The solution involves utilizing jQuery and JavaScript to alter the navigation bar's position based on the scroll position.

Implementation:

  1. HTML:

    <div>
  2. CSS:

    #banner {
      height: 273px;
    }
    
    #nav_bar {
      height: 30px;
    }
    
    $(document).ready(function() {
      $(window).scroll(function () {
        if ($(window).scrollTop() > 550) {
          $('#nav_bar').addClass('navbar-fixed-top');
        }
        if ($(window).scrollTop() < 551) {
          $('#nav_bar').removeClass('navbar-fixed-top');
        }
      });
    });

Further Notes:

  • Adjust the values in the JavaScript (550 and 551) to match the exact scroll position where the navigation bar should fix.
  • This solution can be applied to other elements that need to remain fixed at a specific scroll position.

The above is the detailed content of How do I create a sticky navigation bar that attaches to the top upon scrolling?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn