As you scroll, the header gradually reduces in size, but at the point where the reduction occurs, a slight flick

As I develop a website, I have implemented a sticky header that shrinks after scrolling past the window height. I experimented with two versions - one using Vanilla-JS and another with jQuery. Both versions work fine, but the issue arises when the header starts flickering while slowly scrolling right to the point of transition. Hopefully, the gif provided makes it clear.
https://i.sstatic.net/HrhY2.gif

I have researched about possible problems related to the "sticky-position" property of the header but couldn't find any information regarding flickering at or near the transition point. I would prefer a solution using Vanilla-JS over jQuery since my familiarity is limited with the latter, but I am open to using jQuery if necessary.

Vanilla-JS Version:

function header() {
  Y = window.pageYOffset;
  active = window.innerHeight;
  header = document.getElementById('header');

  if (Y > active) {
    header.classList.add("headerScrolled");
  } else {
    header.classList.remove("headerScrolled");
  }
}

window.addEventListener('scroll', header);
.header {
width: 100vw; 
  position: sticky;
  top: 0;
  height: 15vh;
  background-color: blue;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
  z-index: 9999;
}

.headerScrolled {
  background-color: #fff;
  height: 10vh;
  -webkit-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  -moz-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
}
#s1 {
  height: 100vh;
}
#s2 {
  height: 100vh;
  background-color: gold;
}
<div class="header" id="header">
        <div class="navigation">
            <a>Link</a>
            <a>Link</a>
            <a>Link</a>
          </div>
        </div>
<section id="s1">
  </section>
<section id="s2">
  </section>

jQuery version:

$(document).ready(function() {
$(window).scroll(function() {
  if($(document).scrollTop() > 200) {
    $('.header').addClass('headerScrolled');
    }
    else {
    $('.header').removeClass('headerScrolled');

    }
  });
});
.header {
width: 100vw; 
  position: sticky;
  top: 0;
  height: 15vh;
  background-color: blue;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
  z-index: 9999;
}

.headerScrolled {
  background-color: #fff;
  height: 10vh;
  -webkit-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  -moz-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
}
#s1 {
  height: 100vh;
}
#s2 {
  height: 100vh;
  background-color: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header" id="header">
        <div class="navigation">
            <a>Link</a>
            <a>Link</a>
            <a>Link</a>
          </div>
        </div>
<section id="s1">
  </section>
<section id="s2">
  </section>

Answer №1

Kindly review this code snippet for any discrepancies. It seems that there might be an issue with the headerScrolled height, where the height decreases when the element reaches a certain point and conflicts with the if-else condition. I have used an element here which is positioned such that you can easily add a class to your header.

$(window).scroll(function() {
var targt = $(".target").offset().top;
  if($(document).scrollTop() > targt) {
    $('.header').addClass('headerScrolled');
    }
    else {
    $('.header').removeClass('headerScrolled');

    }
  });
.header {
width: 100vw; 
  position: sticky;
  top: 0;
  height: 15vh;
  background-color: blue;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
  z-index: 9999;
}

.headerScrolled {
  background-color: #fff;
  height: 10vh;
  -webkit-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  -moz-box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  box-shadow: 0 3px 5px rgba(57, 63, 72, 0.2);
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
}
#s1 {
  height: 100vh;
}
#s2 {
  height: 100vh;
  background-color: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="header" id="header">
<div class="navigation">
<a>Link</a>
<a>Link</a>
<a>Link</a>
  </div>
</div>
<section id="s1">

  </section>
<section id="s2">
<div class="target"></div>
  </section>

Answer №2

// I have found success by splitting the code into two separate scripts, allowing for proper functionality without transitions on the display.

$(window).scroll(function() {
        var target = $(".target").offset().top;
    if($(document).scrollTop() > target) {
        $('.header').addClass('headerScrolled');
    }
  });
  
$(window).scroll(function() {
        var target = $(".target").offset().top;
    if($(document).scrollTop() > target) {
    
    }
    else {
    $('.header').removeClass('headerScrolled');

    }
  });

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

How can dat.GUI convert values to degrees within the control panel in Three.js?

In the control panel, I created a basic slider to adjust the position and rotation of an object. Though adjusting the position is straightforward since the values are relative, I want to display the rotation values in degrees. This is the code snippet for ...

Running various callbacks consecutively from an array in JavaScript

I have a series of functions in an array, each one calling a callback once it's finished. For example: var queue = [ function (done) { console.log('Executing first job'); setTimeout(done, 1000); // actually an AJAX call ...

Leverage the NextRouter functionality without the need for a React component

I've created a custom hook that checks if a user is logged in and redirects them to the login page if not. Below is a simplified version of the hook assuming the user is not logged in: import { useRouter } from 'next/router'; export default ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

The conditional statement to check for an empty object does not trigger any actions

My goal is to display a success message once users successfully register without any errors. I have an errors reducer object in Redux that stores errors sent from the backend. The logic is set up so that if the errors object is empty, it shows the success ...

Several HTML videos that have been dynamically added are experiencing issues with muting

I am facing an issue where I have multiple HTML videos added to the DOM using jQuery's append method. My goal is to have these videos inserted in a muted state. The problem lies in the fact that currently, they are not being muted even when I includ ...

Tips for halting the live graph plotting based on a specific condition with canvas js

I have a piece of code that generates a live graph based on probabilities. I am looking for a way to stop the plotting process as soon as a specific condition is met. <script> window.onload = function () { var dps = []; // dataPoints var c ...

What is the best way to position a <td> element within a table row underneath another <td>?

Looking for a solution to ensure Content 3 appears below Content 2 in this block of HTML. Content 1 is extensive and extends far down the page. <table> <tr> <td>(Content 1)</td> <td>(Content 2)</td> ...

The variable req.body.Dates has not been declared

I am currently working on a project that involves dynamically populating two drop down menus using SQL Server. Depending on the selected items, I need to load a specific ejs template using AJAX. My goal is to load data based on the selected criteria. For e ...

Winston is set up to only record .info errors and does not save any errors to a file or a MongoDB database

Currently, I am utilizing express-mongoose as my backend framework and winston as my logging tool. However, I have encountered an issue where winston only seems to log info messages and not errors. The logs can be found in server.log https://i.stack.imgur. ...

A straightforward jQuery conditional statement for dynamically generated content

If the div '#ajax' contains content, I want to make the div '.container' clickable. Here is the basic jQuery script I have implemented: if ('#ajax:empty') { $('.container').css('pointer-events', ' ...

Is it possible to customize the bullet color for an unordered list using li:before?

Recently, I came across a clever solution for changing the color of a bullet point. The method mentioned an alternative approach as well. "If you're unable to edit your HTML, you can opt for list-style-image with a customized colored dot, or utilize ...

Stop modal from opening if a specific element in the modal opener is clicked

I have some code that I'm working with: <div class="owl-item text-center col-lg-6 col-md-6 col-sm-12"> <div class="thumbnail-variant-5 cursor-pointer" data-toggle="modal" data-target=".pz-modal"> <div class="thumbnail-variant-5-i ...

Why is it necessary to include 'export' when declaring a React component?

When working with React (ES6), there seems to be two variations that I encounter: class Hello extends React.Component { ... } and sometimes it looks like this: export class Hello extends React.Component { ... } I'm curious about the significance o ...

Tips for maintaining consistent image dimensions while resizing your browser window

I'm having trouble preventing an image from resizing when I adjust the browser size. If you click on this link and try resizing your browser, you'll see what I mean - the image stays the same. I've attempted various methods but haven't ...

Ways to Adjust Website Scaling for Varying Screen Sizes

Is there a way to adjust my website's scale based on the device width, such as changing it to 0.7 for certain devices? The only information I've found so far is using the <meta> tag: <meta name="viewport" content="width=device-width, i ...

Accessing a variable from another HTML using JavaScript

I'm currently attempting to access a variable from another HTML file using JS. Specifically, I have a file (file1.htm) that opens a dialog box, and I want to send the information of the selected file to another file (file2.htm) in order to modify a v ...

Having difficulty receiving a response from an AJAX call within the success function

After browsing through this stack link Ajax response not calling success:function() when using jQuery 1.8.3, I'm puzzled as to why the success function is not invoked when I uncomment the dataType line. It seems that setting dataType = JSON prevents t ...

Displaying HTML with AngularJS dynamic data-binding

Here is a sample view: <div ng-show=""> <div style='background-color: #13a4d6; border-color: #0F82A8'> {{headerdescription}} <div style='float: right'>{{price}} $</div> </div> <div style=&apos ...

Attempting to create a dynamic layout for the objects using media queries and flexbox, however, the results are not as expected

.container { display: flex; justify-content: center; align-items: center; flex-wrap: wrap; flex-direction: column; } .item { margin: 10px; border: 1px solid lightgray; border-radius: 10px; overflow: hidden; width: 100%; } @media scree ...