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

DDD
Release: 2024-10-31 11:38:01
Original
282 people have browsed it

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>
Copy after login

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

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

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>
Copy after login

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>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template