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
Release: 2024-11-19 13:40:02
Original
634 people have browsed it

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>
    Copy after login
  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');
        }
      });
    });
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template