Header with Sticky Behavior and Smooth Slide Down Animation

I am trying to achieve a scroll effect on my page where the header will move up when scrolling up, but at position 150 it should smoothly slide down and stay fixed at the top. I have tried various methods but haven't been able to get it right. Can someone take a look at my code?

Something similar to this , although this script has some issues.

jQuery(document).ready(function ($) {
    $(window).scroll(function () {

        if ($(window).scrollTop() >= 100) {
            $('.navarea').addClass('fixed-header');

        } else {
            $('.navarea').removeClass('fixed-header');
        }
    });
});

Here is the CSS:

.navarea {

    z-index: 2;
    background: rgba(255, 255, 255, 0.9);
    transition: all 0.5s ease-in-out;
}

.fixed-header {
    position: fixed;
    background: rgba(255, 255, 255, 0.9);
    text-shadow: none;
    padding-bottom: 0;
    top: 0;
    z-index: 5;
    transition: all 0.5s ease-in-out;
}

View live demo here: https://codepen.io/pagol/pen/XovvGJ

Answer №1

Here's an example showcasing:

  • Creating a deep clone of the navigation element with a successful outcome after extensive testing
  • Implementing CSS3 transition for the cloned navigation
  • Utilizing a debounce callback mechanism to optimize functions triggered on scroll events
  • Enhancing the effect by using position sticky and visibility for the original element

// https://github.com/micro-js/debounce/blob/master/lib/index.js
function debounce(fn, time) {
  var pending = null
  return function() {
    if (pending) clearTimeout(pending)
    pending = setTimeout(run, time)
    return function() {
      clearTimeout(pending)
      pending = null
    }
  }
  function run() {
    pending = null
    fn()
  }
}

function documentScrollTop() {
  const doc = document.documentElement;
  return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
}

const el_nav1 = document.getElementById("nav");
const el_nav2 = el_nav1.cloneNode(true);
el_nav1.parentNode.insertBefore(el_nav2, el_nav1);
el_nav2.style.cssText = `position:fixed; transform:translateY(-100%);`;

function animateNavigation() {
  const canShow = documentScrollTop() >= 150;
  el_nav2.style.transform = `translateY(${canShow?0:-100}%)`;
  el_nav1.style.cssText = `position:${canShow?'sticky':'relative'}; visibility:${canShow?'hidden':'visible'};`
}

window.addEventListener('scroll', debounce(animateNavigation, 99));
document.addEventListener('DOMContentLoaded', animateNavigation);
/*QuickReset*/ *{margin:0;box-sizing:border-box;} html,body{height:100%;font:14px/1.4 sans-serif;}
p {height:300vh;border:4px dashed #000;} /* force scrollbars */

#nav {
  position: relative;
  top: 0;
  width: 100%;
  padding: 20px;
  background: gold;
  transition: transform 0.6s;
}
<nav id="nav">NAVIGATION HERE</nav>
<p></p>

Areas for potential enhancement

  • Consider using only one element to simplify the implementation (challenging for scroll back to top functionality)
  • Add an extra condition inside the animateNavigation function to check if an action has already been executed (preventing redundant calls to style until canShow changes value)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The overlay only covers a portion of the page

I'm currently working on a new webpage and have found the perfect background image. However, I would like to add an overlay to darken the image. Unfortunately, the overlay doesn't cover the entire page! Despite my attempts, I haven't been s ...

Strange Safari 15 bug causing unexpected transformations

Hey there, I'm a div with animation on scroll using GSAP. On Safari 15 (no issues below 15), something strange is happening - parts of the letters are leaving an afterimage on the sides. The code snippet I am using for this animation is: this.$refs.l ...

jQuery function fails to work on a list that has been dynamically generated

Can someone please assist me? I have encountered an issue where the dynamic list on the second page is not functioning properly. When I click any "li" element to trigger an alert for the respective "id" (which works fine for a hardcoded list), nothing happ ...

Utilize AngularJS to modify the appearance of text

Just starting out with AngularJS and I need to achieve the following task. I have a text that says "bob" and two buttons, one for bold and one for italic. When the bold button is clicked, I want to make the text BOB bold and when the italic button is click ...

Troubles with Conditional Application of CSS Styles to a Twitter-Bootstrap Table

I am facing an issue with highlighting a row in a table when a barcode is entered. Despite following similar scenarios and checking my code, the CSS doesn't seem to be applied. Can anyone help me figure out what I'm missing or how I can fix this? ...

The iframe content is not updating despite using jQuery

On this site , the following code is present: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <iframe style="position: absolute; top: 0; left: 0; height: 100%; width: 100%" src="blank.html"></iframe ...

Discovering a specific element using jQuery

I am trying to work with a div structure like this: <div class="country"> <div class="cty_popover"> <p>TITLE</p> <ul> <li>NAME 1</li> <li>NAME 2</li> ...

When an image is loaded, use Jquery to automatically open a new tab, instead of

I need to implement a function where, on loading an image on a page, a new tab opens and starts downloading a file from a specific URL while keeping the original page open. This task is part of a WordPress site with a jQuery section in the backend. I' ...

Remove elements generated by the .after method with Jquery

In my HTML file, I have a table with hard-coded column headers: <table id="debugger-table"> <tr> <th>Attribute</th> <th>Computed</th> <th>Correct</th> </tr> </table&g ...

When making an ajax call, I passed the data "itemShape" but on the URL page, an error appeared stating "Undefined index: itemShape"

Hello, I have been using an Ajax function to send data with the key itemShape. However, when I directly access the URL page or service page, it displays the following error: Notice: Undefined index: itemShape in C:\wamp64\www\inventory_so ...

A HTML List with Five Columns

Why isn't the CSS code filling up 100% of the screen? I have 5 columns with a width of 20% floating left. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset= ...

Identify when a request is being executed using AJAX by checking the URL

My current code includes multiple ajax requests from various JavaScript files. I am looking for a way to identify specific ajax requests and interrupt their execution in order to prioritize a newer one. Is it possible to detect and stop ajax requests based ...

The information window is malfunctioning on Google Maps

I created buttons that are linked to specific locations on a map and they seem to be functioning, although not in the most efficient way. However, when attempting to add an info window to appear on the marker, it does not work as expected. I am unsure of ...

The current state of my DOM doesn't match the updated value in my model. The update is triggered by a function that is called when a button is clicked

app.controller('thumbnailController', function ($scope) { debugger $scope.customers = [ { name: 'Ave Jones', city: 'Phoenix' }, { name: 'Amie Riley', city: 'Phoenix&ap ...

Navigating through a PHP table, tracking your progress with a

I have encountered a problem that I need help with. I have been searching the internet for information on how to add a progress bar to my PHP code. Most solutions I found use the style method to display the progress percentage. In the image below, you can ...

What is causing the label's color to remain the same?

Once the page has loaded, the label color (which reads "enter your name") is supposed to change to red. However, despite the script being in place, the color remains unchanged. What could be the reason for this? SCRIPT window.onload = initiateScript; fu ...

Using Ajax to Retrieve JSON Data with jQuery

I've created a jQuery function to retrieve a district_id and authority name for a form that I have developed. When the user clicks on search using a postcode, it fills in the box with the postcode. However, when I attempt to populate the district_id ...

Sending the complete data from an HTML table to a web method

Is there a way to pass the data from a dynamically generated HTML table grid to a web method using jQuery AJAX? The table grid creates multiple rows on button click at runtime, and I need to send the entire table data. Please refer to the following snaps ...

Combining various formats within a single Ajax PHP webpage

Having trouble articulating my needs to Google due to language barriers, I am seeking your help. I aim to display three forms on a single page without refreshing it. The first form submits its action to PHP, which then determines the function to show (alon ...

Tips for adjusting the width of an HTML element that is set to position: fixed

<div class="ui-datatable-scrollable-view" style=" width: 100%; position: relative; "> <div class="ui-widget-header ui-datatable-scrollable-header" style="position:fixed;top:50px"> </div> </div> ...