How to Create a Fixed Header on Scroll Using CSS and JavaScript?

Linda Hamilton
Release: 2024-11-01 04:34:28
Original
601 people have browsed it

How to Create a Fixed Header on Scroll Using CSS and JavaScript?

Creating a Fixed Header on Scroll Using CSS and JavaScript

In this scenario, we aim to create a header that becomes fixed and remains in place when scrolled beyond a certain point.

CSS and HTML Approach

Using only CSS and HTML is not sufficient to achieve this functionality. CSS alone does not provide a solution for attaching an element to a specific scroll position.

JavaScript Integration

To fix a header on scroll, JavaScript is required for event handling. The following steps outline the solution:

  1. Define the Fixed Position Class:

    <code class="css">.fixed {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
    }</code>
    Copy after login
  2. Assign the Class on Scroll:

    <code class="javascript">$(window).scroll(function() {
        var sticky = $('.sticky'),
            scroll = $(window).scrollTop();
    
        if (scroll >= 100) {
            sticky.addClass('fixed');
        } else {
            sticky.removeClass('fixed');
        }
    });</code>
    Copy after login

    Here, when the scroll position exceeds 100 pixels, the 'fixed' class is added to the '.sticky' element, fixing it in place.

Example:

The following HTML code defines a fixed header:

<code class="html"><div class="sticky">Header</div></code>
Copy after login

Demo:

[Fiddle Demo](https://jsfiddle.net/gxRC9/501/)

Extended Example:

If the trigger point should occur when the sticky element reaches the top of the screen, we can use offset().top:

<code class="javascript">var stickyOffset = $('.sticky').offset().top;

$(window).scroll(function() {
    var sticky = $('.sticky'),
        scroll = $(window).scrollTop();

    if (scroll >= stickyOffset) {
        sticky.addClass('fixed');
    } else {
        sticky.removeClass('fixed');
    }
});</code>
Copy after login

Extended Demo:

[Extended Fiddle Demo](https://jsfiddle.net/gxRC9/502/)

The above is the detailed content of How to Create a Fixed Header on Scroll Using CSS and JavaScript?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!