Home > Article > Web Front-end > 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:
Define the Fixed Position Class:
<code class="css">.fixed { position: fixed; top: 0; left: 0; width: 100%; }</code>
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>
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>
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>
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!