Header misalignment occurs when the user scrolls up too quickly causing it to display

One interesting feature on my website is that the header disappears as users scroll down the page, but reappears when they start scrolling back up, even if they are halfway down. However, if a user quickly scrolls up and down, there seems to be an issue with the code not reacting fast enough, resulting in the "detached" class being added unnecessarily. As a result, the red background remains visible even when at the top of the browser.

If you have any suggestions or solutions on how to improve this script, please feel free to share! You can view the markup, css, and javascript on this CodePen link: http://codepen.io/anon/pen/QpWXpj

I appreciate any help you can provide. Thank you!

Answer №1

You must remove the

if (!currentScroll) {
    header.removeClass('detached');
}

from the else section to ensure that the menu jump fix is active at all times, not just when the else condition is met.

For the updated codepen, please see: http://codepen.io/nashcheez/pen/KWKjjq

Therefore, your js code should look like this:

/* ==========================================================================
   #SHOW/HIDE HEADER
   ========================================================================== */

$(function() {

  var previousScroll = 0, // previous scroll position
    menuOffset = 70, // height of menu (once scroll passed it, menu is hidden)
    detachPoint = 220, // point of detach (after scroll passed it, menu is fixed)
    hideShowOffset = 5, // scrolling value after which triggers hide/show menu
    header = $('.page-head');

  $(window).scroll(function() {

    if (header.hasClass('expanded')) return;

    var currentScroll = $(this).scrollTop(),
      scrollDifference = Math.abs(currentScroll - previousScroll);

    // if scrolled past menu
    if (currentScroll > menuOffset) {
      // if scrolled past detach point add class to fix menu
      if (currentScroll > detachPoint) {
        var value = parseInt(header.css('transform').split(',')[5]);
        console.log(value);
        if (!header.hasClass('transitioning') && !header.hasClass('detached') && value != -110) {
          header.addClass('transitioning').one('transitionend', function() {
            console.log('transitionend');
            header.removeClass('transitioning');
            if (currentScroll > detachPoint) header.addClass('detached');
          });
        } else if (!header.hasClass('transitioning') && !header.hasClass('detached')) {
          header.addClass('detached');
        }
      }

      // if scrolling faster than hideShowOffset hide/show menu
      if (scrollDifference >= hideShowOffset) {
        if (currentScroll > previousScroll) {
          // scrolling down; hide menu
          if (!header.hasClass('invisible'))
            header.addClass('invisible');
        } else {
          // scrolling up; show menu
          if (header.hasClass('invisible'))
            header.removeClass('invisible');
        }
      }
    } 
    // only remove “detached” class if user is at the top of document (menu jump fix)
    if (!currentScroll) {
        header.removeClass('detached');
      }

    // If user is at the bottom of document show menu.
    if ($(window).height() + currentScroll == $(document).height()) {
      header.removeClass('invisible');
    }

    // Replace previous scroll position with new one.
    previousScroll = currentScroll;
  });
});

/* ==========================================================================
   #SHOW/HIDE NAVIGATION
   ========================================================================== */

/* 
 * Creates classes to enable responsive navigation.
 */

// Wait for the DOM to be ready (all elements printed on page regardless if 
// loaded or not).
$(function() {

  // Bind a click event to anything with the class "toggle-nav".
  $('.page-head__toggle').click(function() {
    if ($('body').hasClass('show-nav')) {
      $('body').removeClass('show-nav').addClass('hide-nav');

      setTimeout(function() {
        $('body').removeClass('hide-nav');
      }, 500);

    } else {
      $('body').removeClass('hide-nav').addClass('show-nav');
    }
    // Deactivate the default behavior of going to the next page on click.
    return false;
  });
});

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

Could Knockout's value binding potentially lead to a script injection vulnerability?

My understanding is that knockout effectively deals with this scenario, but I just want to double-check. Is it correct to assume that when using the value binding with a form control such as input/textarea, there is no risk of a script injection attack? O ...

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

The some() method in Javascript with an extra argument

I want to validate if at least one element in an array satisfies a certain condition. The condition is based on a variable. Here's an example of how I'm currently attempting this: function checkCondition(previousValue, index, array) { retur ...

iOS 7.0.x causing issues with the height of tabs being trimmed

Struggling to fix a nightmare of an issue with my app, so I'm reaching out for some help. Everything is working fine on Android and iOS versions 7.1.x, 8, and 9. However, when installed on iOS 7.0.4, the bottom tabs are getting cut off. See below: O ...

Upon pressing enter in the input box, the page will redirect to localhost:3000/

Utilizing the NewYorkTimes API to retrieve search queries from an input field. However, upon hitting enter after entering a query, my localhost reloads and redirects to localhost:3000/?. After using console.log(url) in the console, I confirmed that the UR ...

Customizing Vue: Implementing an automatic addition of attributes to elements when using v-on:click directive

We are currently working with single file Vue components and we're facing a challenge in our mousemove event handler. We want to be able to determine if the target element is clickable. Within our Vue templates, we utilize v-on directives such as: v- ...

What is the best way to retrieve specific items using the Chosen JQuery plugin?

I have a multiple select box set up with chosen, but I am unsure how to retrieve the selected items. <select class="multiselect" multiple="" name="parlementId"> @foreach (Politicus p in politici) { <optio ...

Last item in Material UI Grid container not filling up entire space

I designed a Grid container with 2 Grid columns, each containing 3 elements. However, I am facing an issue where the last element of each column is not appearing at the bottom as intended. What could be causing this problem? For reference, you can view th ...

Exploring through a table using JavaScript

I am struggling to search a table within my HTML for a specific term. The code I have works to an extent, but it does not account for alternatives such as searching for "what is that" when I type in "What is that". Additionally, I need the script to ignor ...

Running a JS/JSON function in Snowflake that results in a syntax error

Can anyone help me troubleshoot the issue with the following function? I am receiving this error message: SQL compilation error: syntax error line 1 at position 0 unexpected 'function'. Should I be using JSON Script or Javascript for this? func ...

Vue-router vulnerability allowing for DOM-based open redirects

I am currently working on a Vue application that was created using Vue-cli. Vue version: 2.6.11 vue-router version: 3.2.0 Link for Reproduction https://github.com/keyhangholami/dom-based-open-redirect Instructions to replicate To reproduce the i ...

Updating a nested object in MongoDB using Mongoose and calling the markModified method

Regrettably, I am lacking a suitable record to carry out a test on this. Furthermore, I have been unable to locate any information related to this particular issue. Let's consider a scenario where I have a document structured as shown below: { ema ...

"Implementing CSS inline styles for improved appearance on a Safari browser when visiting

Having some trouble using CSS to create rounded corners on my Facebook fan page. Everything works fine except for Safari browser. I've tried inline styles and a separate stylesheet, but no luck. Any help would be appreciated. My CSS for rounded corne ...

Issues arise when using ng-repeat in conjunction with ng-click

I am facing some new challenges in my spa project with angularjs. This is the HTML snippet causing issues: <a ng-repeat="friend in chat.friendlist" ng-click="loadChat('{{friend.friend_username}}')" data-toggle="modal" data-target="#chat" d ...

Tips for successfully transferring large amounts of data using XmlHttpRequest in ajax calls

I'm facing an issue with passing a large amount of data to the controller using XmlHttpRequest. Here's the code snippet I've implemented: var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = ...

Arrangement of items in a grid with various sizes

I have encountered a challenge that I cannot seem to overcome. In my grid system, there are 18 identical items/boxes. I am looking to remove 4 of those items/boxes and combine them into one large item/box. Refer to the wireframe below for guidance on how ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Unable to locate a declaration file for the module "../constants/links" in src/constants/links.js, as it implicitly defaults to type 'any'

Within my VueJS application, I have brought in some constant variables. <script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator' import { MOON_HOLDINGS_LINK, TWITTER_LINK } from '../constants/links' @Comp ...

Using Vue.js within Cordova platform allows developers to create dynamic

Having trouble integrating a Vue.js app into Cordova. Everything seems to be working fine, except I'm unsure how to capture Cordova events (deviceready, pause, etc.) within my Vue application. Using the Webpack template from vue-cli. This is my file ...