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

Overlap of sub menus

Seeking assistance from a CSS expert for a challenge I am facing. I am currently working on a toggle menu for mobile view, and encountering issues with the submenu. Any list item placed below another one with children is not visible. Removing the parent l ...

Is there a way to alter multiple classes using hover effect on a single class without the use of JavaScript, only employing

Hello there! I have a question about applying styles to specific classes when hovering over certain elements. Unfortunately, I am unable to make changes to the HTML files and can only work with the CSS file. Take a look at the image below for reference: ht ...

Resetting the Countdown Clock: A Transformation Process

I have implemented a countdown timer script that I found online and made some adjustments to fit my website's needs. While the current setup effectively counts down to a specific date and time, I now require the timer to reset back to a 24-hour countd ...

allowing absolutely positioned region to expand

For further information, please visit this page: test page In the process of designing a website, I have implemented a sidebar featuring an accordion style vertical navigation bar. The sidebar is set to be absolutely positioned in relation to its containi ...

Issues with Google maps are causing multiple maps to malfunction

After incorporating some jquery code to create multiple maps upon window load, I noticed a peculiar issue with the maps - they all display the same location despite having different latitudes and longitudes set. Upon inspecting the code responsible for cr ...

HTML makes column text wrapping automatic

Is it feasible to implement text wrapping into two columns or more in HTML using solely CSS? I have a series of continuous text enclosed within p tags only, structured as follows: <div id="needtowrap"> <p>Lorem ipsum dolor sit amet, ...&l ...

Can CSS Grid be substituted for Material UI's grid component?

Exploring the Material-UI Grid Component, I have found that it is built on flexbox and offers great functionality. However, my curiosity lies in comparing it to CSS Grid, which I find equally user-friendly. Despite my preference for CSS Grid, I am hesita ...

The request response was a JSON object that started with the keyword "POST"

My frustration is growing as I encounter a strange issue with the stack template I purchased from envato market. Every time I attempt a simple ajax request, the json returned from my PHP script seems to be invalid. Interestingly, the exact same code works ...

The Excel document became corrupted after downloading through a ReactJs jQuery ajax post request

Attempting to download a file using jQuery AJAX post request from ReactJs, with an express router middleware layer utilizing the Request API to send requests to a Spring Boot REST API. The flow goes like this: AJAX => Express POST route => Spring Boot API. ...

Tips for preventing overlap between two divs when utilizing position: absolute in CSS

In this CodePen link [https://codepen.io/anon/pen/qvQpaY], there is an issue with overlay between the two divs that have a class name of box-container. The black rectangle is being counted as the overall height by box-container because the red rectangle is ...

Tips for preventing text wrapping in off-canvas design

Seeking advice for my Web Application prototype - looking to prevent text wrapping in off-canvas menu paragraphs using CSS or JS. New to building this type of menu, I used an example from W3Schools to achieve the current design. <!DOCTYPE html> ...

Implementing a dynamic function with jQuery Tokenize's change event

I'm currently facing an issue with triggering the on change event on the select box from jQuery Tokenize. Below is the code snippet I am working with: <select id="tokenize" multiple="multiple" class="tokenize-sample"> <option value="1"&g ...

The hover effect on the menu button is not covering the entire button when the screen is resized

It appears that I am encountering a problem with the hover functionality. When my screen is at full size, hovering over a menu option causes the entire background color to change. However, upon resizing the screen, only a part of the background color chang ...

Troubleshooting problem with media queries in CSS

As a newbie to HTML and CSS, I've been encountering difficulties with media queries. My website seems to only function properly when viewed in a resolution of 1920x1080, so I attempted to implement some media queries in my CSS to cater to other resolu ...

What is the best way to ensure my image adjusts its width and height responsively?

How can I make my image responsive to the size of the container, adjusting not just the width but also the height to fit in a container with a max-width of 1300px? I have created a test image with dimensions of 400px height and 1300px width. Take a look a ...

Combining data from various JSON files to create dynamic charts with Highcharts

At this moment, my Highchart code is set up in a way where I want to replace the static data-series values within the HTML file with information loaded from a JSON file. The current code appears as follows: <!doctype html> <script type="text/jav ...

Eliminating the appearance of horizontal scroll bar by employing transform scale to zoom out

When you run the code provided in the link below and scale down the HTML to 50% while increasing the width to fit the window, a scrollbar becomes visible. This only occurs in Chrome and not in Firefox. Click here The content of the DOM can be modified and ...

Issue with styling Icon Menu in material-ui

I'm having trouble styling the Icon Menu, even when I try using listStyle or menuStyle. I simply need to adjust the position like this: It currently looks like this: Update: Here's an example: import React from 'react'; import IconM ...

Trimming Picture on User's Device

Currently, I am utilizing the jQuery ImgAreaSelect 0.9.10 plugin to crop images that are uploaded by users. The data input format being used is "multipart/form-data". Upon cropping an image with the plugin, it provides me with coordinates in pixels. Howev ...

Unsure about the jQuery val function

I thought that utilizing val would automatically assign the value to any text box specified in the selector. I have multiple input text boxes and want them all to be assigned values using val: <input type="text" id="firstName" name="firstName" size="20 ...