Home  >  Article  >  Web Front-end  >  How to Create a Sticky Header with CSS and JavaScript Without jQuery?

How to Create a Sticky Header with CSS and JavaScript Without jQuery?

DDD
DDDOriginal
2024-10-31 11:38:01208browse

How to Create a Sticky Header with CSS and JavaScript Without jQuery?

Fixing Headers on Scroll

When creating a header that remains visible despite scrolling, it's possible to implement this behavior using CSS and HTML alone without the need for jQuery.

CSS and HTML Solution

Introduce a sticky header class:

<code class="css">.sticky-header {
  width: 700px;
  height: 50px;
  background: orange;
  position: fixed;
}</code>

In your HTML, add a div with the "sticky" class:

<code class="html"><div class="sticky"></div></code>

JavaScript for Scroll Events

For precise control over the header's fixation, JavaScript is necessary for scroll events:

<code class="javascript">$(window).scroll(function() {
  var sticky = $('.sticky'),
    scroll = $(window).scrollTop();

  if (scroll >= 100) {
    sticky.addClass('fixed');
  } else {
    sticky.removeClass('fixed');
  }
});</code>

Extended Example

To determine the fixation point based on the sticky element's position on the screen, use offset().top:

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

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

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

The above is the detailed content of How to Create a Sticky Header with CSS and JavaScript Without jQuery?. 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