Display or Conceal Sub-Header according to Scrolling Position

Question: My goal is to create a specific animation on my website. When loading the page on mobile, I want to display the div with ID "sub-header", but once the user scrolls more than 50px down, I want to hide it. Additionally, if the user scrolls up by 60px at any point while on the page, I want to show sub-header again.

The Issue I am Facing: The menu hides as expected when scrolling down, but when scrolling back up, it repeatedly shows and hides multiple times.

JQuery Code:


var newScroll = 0;
var subHeaderPosition = true;
var currentScroll = 0;

$(window).scroll(function () {
    currentScroll = $(window).scrollTop();

    if ($(window).width() < 779) {
       if (currentScroll > 50 && subHeaderPosition) {
           console.log("Current Scroll position: " + currentScroll);
           console.log("Hiding Sub-Header");
           $("#sub-header").hide(300);

           subHeaderPosition = false;
           newScroll = $(window).scrollTop();
           console.log("New Scroll position: " + newScroll);
        } else if ((currentScroll - 60) < newScroll && !subHeaderPosition) {
            console.log("Scroll position: " + currentScroll);
            console.log("Showing Sub-Header");
            $("#sub-header").show(300);
            subHeaderPosition = true;
            newScroll = $(window).scrollTop();
         } else {
             newScroll = $(window).scrollTop();
         }
     }
});

UPDATE: Upon further investigation, I noticed that 'newScroll' and 'currentScroll' always have the same value, which gives me some insight into where the problem might lie. I will share a solution once I find one, but I'm open to suggestions from others as well.

Answer №1

If you are looking to resolve a certain problem, try using this solution:

$(function(){

$(window).on('scroll', function(){

    if($(window).scrollTop() >= 50){
    $('header').addClass('hide');
}
else if($(window).scrollTop() <= 60){
    $('header').removeClass('hide');
}

});

});

https://jsfiddle.net/qummetov_/3hf1e350/

Answer №2

It appears that there is an issue with the timing of hide/show actions. This results in the hide action being completed while the scroll function continues asynchronously.

To see a demonstration, visit this jsfiddle.

I am confirming the accuracy of this using the variable canShowHeader. In my example, I am simulating a delay with setTimeout, but you can refer to the original jquery show/hide documentation:

For instance:

$( "#book" ).show(300, function() {
  canShowHeader = false;
});

and

$( "#book" ).hide(300, function() {
  canShowHeader = true;
});

I hope this explanation helps clarify the situation...

Answer №3

Considering the suggestion by @Ниязи Гумметов, I am contemplating using addClass and removeClass because each class can only be added or removed once.

Here is a potential implementation:

var newScroll = 0;

var subHeaderPosition = true;

var currentScroll = 0;

$(window).scroll(function() {

  currentScroll = $(window).scrollTop();


  if (currentScroll > 50 && subHeaderPosition) {

    console.log("Current Scroll position: " + currentScroll);

    console.log("Hide the scroll");

    $("#sub-header").removeClass("show");
    $("#sub-header").addClass("hide");

    subHeaderPosition = false;

    newScroll = $(window).scrollTop();

    console.log("New Scroll position: " + newScroll);

  } else if ((currentScroll - 60) < newScroll && !subHeaderPosition) {

    console.log("Scroll position: " + currentScroll);

    console.log("Show Sub-Header on scroll");

    $("#sub-header").addClass("show");


    subHeaderPosition = true;

    newScroll = $(window).scrollTop();

  } else {

    newScroll = $(window).scrollTop();
  }


});
#sub-header {
  margin-top: 500px;
  transition: all .3s;
  opacity: 1;
  visibility: visible;
}
.hide {
  opacity: 0;
  visibility: hidden;
}
.show {
  opacity: 1 !important;
  visibility: visible !important;
}

Alternatively, you can explore Underscore Throttle as suggested by nicholaides.

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

Issues with interpreting PHP within HTML documents

I'm having trouble using PHP on my HTML page. I've added AddType application/x-httpd-php .html to the .htaccess file as recommended, but when I try to access the page in a browser, a dialog box pops up asking if I want to save the file or open it ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Trouble with SCSS Nesting

Can anyone help me with styling an H3 and a p tag within a div? I'm facing an issue where the p tag is not being styled in this code block: .marketing-single-page-titles{ h3 { margin: 0; padding: 0; p { margin: 0; padding: 0; position: rel ...

"What is the best approach for setting up an Azure Web App to host both an Express static site and API

Setting up an Express app was a breeze for me, but when it comes to deploying it on Azure Web App, I'm hitting some roadblocks! The structure of my app is quite simple: a static web app with its own API. Requests to /website.com/api are forwarded to ...

Is there a solution for the noticeable delay in loading fonts on a web page?

I've encountered an issue in my React project where a Google font I'm using seems to briefly load as a different font before switching to the correct one. How can I prevent this from happening? This is how I'm loading the font in public/ind ...

Verify the response retrieved from the ajax call and conduct a comparison

I'm struggling with the following code. Whenever I submit a form, I want to display a modal view. The modal view is functioning correctly, but it keeps showing the same one every time I submit. The #status1 returns a modal view with success markup a ...

Vue.js does not apply the "selected" attribute to set the HTML <option> tag to default

Trying to designate a default <option> tag from the available options. Utilizing v-model on the <select> tag, the vue.js documentation indicates the following approach: v-model will disregard the ... selected attributes present on form ele ...

Resolving Issues in HTML and the Dynamic Duo of PHP and MySQL

Hey there, I've been a reader for a while now but this is my first time posting. I'm really into PHP and I've been working on a page lately. Right now, I've got the DB connection set up nicely and my SELECT statement is doing exactly wh ...

Fluctuating Values in Array Distribution

I have a set of users and products that I need to distribute, for example: The number of values in the array can vary each time - it could be one value one time and three values another time. It is important that each user receives a unique product with ...

Modifying a string in PHP before inserting it into a database

I am looking to save a method for performing a specific task in a database field. However, I want to store this method as a string including HTML tags. For instance, the following list should be included: <ul> <li>List item</li> <li&g ...

Speed up the opening and closing of a div element on mouse hover

Looking to create a smooth delay for opening and closing a div when mouse hover. Here is the code I have: function show_panel1() { document.getElementById('hoverpanel1').style.display="block"; } function hide_panel1() { document.getElementByI ...

I'm having trouble getting the HTML checkbox symbol to show up correctly. My goal is to create all the elements using the DOM

I am currently building all of my elements manually through the DOM tree, and I am attempting to insert a checkbox symbol in this manner: //Add date var tdDate = document.createElement("td"); tdDate.textContent = ("" + workoutList[idx].date); ...

Incorporate Vue into a template using variables and props

Currently in the process of building a vue app and wondering how I can seamlessly integrate it into a template while passing variables (props) into it. When I execute npm run dev, the app and all its components are coded with no issues. After running npm ...

After clicking the 'add row' button, I successfully added a new row; however, the jQuery date

I encountered an issue with the datepicker when adding it to dynamically added rows. The datepicker was not functioning properly on the added rows, except for the first row where it worked perfectly. Strangely, removing the first row resulted in the datepi ...

Establish the starting time for the timer and use the setInterval() function according to the seconds stored within the object

How can I configure the values of timerOn, timerTime, and timerStart to make the watch start counting from 120 seconds? Currently, the clock starts counting from 3 minutes and 22 seconds, but it should start from 2 minutes. You can find all the code here: ...

The React.js project I created is showcased on GitHub pages and has a sleek black design

After developing a project using React.js and deploying it on github pages, everything was functioning smoothly. However, I encountered an issue where the screen turned black after logging in and out multiple times. Are there any suggestions on how to reso ...

How to effectively utilize wrapAsync in MeteorJS when working with callbacks in the vzaar API?

Issue to Resolve: My current challenge involves retrieving an uploaded video ID asynchronously from an API in order to incorporate it into my code once the video upload process is completed. Unfortunately, I am encountering issues where the returned value ...

Certain cases will see success with iPhone jquery/ajax functionality, while others may encounter

I am facing an issue with multiple pages in my project that utilize AJAX to submit a form to django. While the buttons work perfectly on various platforms and browsers like Chrome, Firefox, and desktop Safari, they seem to malfunction specifically on mobil ...

How can we tally the content in the drop area using JQuery Drag and Drop?

Currently, I am developing a Jquery project that involves allowing the user to drag a 'pill' into a 'cup', and then displaying the number of pills in the cup. However, I am encountering an issue where if the user moves a pill once it&ap ...

Incorrect Calculation of CSS Grid Container Width in Firefox

When using this CSS Grid code, there is a difference in behavior between Chrome and IE compared to Firefox. https://codepen.io/inkOrange/pen/XGzeMo This layout is intended to scroll horizontally when the content overflows beyond the fixed container size o ...