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

Minify Magic Dreamweaver Plugin

Does anyone know of a plugin that can minify javascript or css files as they are uploaded using Dreamweaver or similar coding software? For example, if I create a file like functions-global.js, the plugin would upload the original file and also generate a ...

Angular: Leveraging real-time data updates to populate an Angular Material Table by subscribing to a dynamic data variable in a service

Seeking guidance on how to set up a subscription to a dynamic variable (searchData - representing search results) for use as a data source in an Angular Material Table. I have a table-datasource.ts file where I want to subscribe to the search results from ...

4 products - all discounted by 25% - featuring stylish borders and margins

After extensively searching the internet, I have come across similar issues but not quite the same as mine. I have a list that I want to display in table form within a parent div taking up the entire width (100%). I aim to show 4 items per row and attempt ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

forward various submit buttons to separate pages

I created a form in HTML with multiple choices, and I want each choice to redirect the user to a different page once clicked. Can anyone advise me on how to achieve this? I am coding in PHP. echo "<form action='home.php' method='po ...

Tips on retrieving Bootstrap selectpicker value by using loops in Jquery

I am attempting to perform a basic validation using jQuery, where I need to iterate through all elements to check for the existence of values. The validation script is working well except for the jQuery selectpicker functionality. Here's what I have t ...

Tips on displaying the entire text when hovering over it

I'm facing an issue with a select element that retrieves options from an API. The problem is that some options are too large for the text box and get cut off, making them hard to read for users. <div class="form-group my-4"> <lab ...

What is the method to determine the height of a Bootstrap Popover?

Can anyone help me figure out how to determine the height of a Popover? I have only been able to find the width so far. I need to know the Popover height in order to resize the DIV height accordingly. Note: Using Bootstrap 2.x ...

Unexpected resizing of DIV element in Chrome

Working on my new PHP website, I encountered a strange issue recently. I have a file for the top navbar that is included on every page and it was functioning perfectly fine. However, while creating a register form, I noticed something odd happening. When r ...

Using Ruby instead of Javascript in lessc

My CSS is compiled in a node application using lessc. LESS was installed via NPM. When I check the current version of lessc --version it shows lessc 1.3.3 (LESS Compiler) [Ruby] 2.3.2 How can I change it to display lessc 1.3.0 (LESS Compiler) ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

The issue I am facing is that the "return false" statement does not seem to be effective in my jQuery AJAX

Apologies to everyone.. :( it seems I missed including the jquery library... My bad! :3 Feeling quite exhausted at the moment. Could someone please point out what's wrong with my code? The 'returning false' isn't functioning as expecte ...

Live JSON sign-up feature on site

Is there a way to retrieve user email in real-time without using JSON? Currently, I am utilizing JSON for this purpose but it poses the risk of exposing emails that are stored in $resEmailsJson. Ideally, I would like to find a solution to hide all JSON $ ...

Next.js presents a challenge with micro frontend routing

In the process of developing a micro frontend framework, I have three Next.js projects - app1, app2, and base. The role of app1 and app2 is as remote applications while base serves as the host application. Configuration for app1 in next.config.js: const ...

Using jQuery and regular expressions to replace placeholders with dynamic values

I need some help with replacing custom variable tags in a content block using values from an array. Currently, my code successfully replaces variables that look like %([variable_name])%, but I also need it to replace variables in the format <%[variable_ ...

Popup window displaying website content upon DOM loading, ensuring compatibility across various browsers

I am facing a challenge with my HTML popup window where I need to add text after opening the window using a specific function: var win = window.open('private.php', data.sender_id , 'width=300,height=400'); win.win ...

Is the table scrollable within the tbody tag?

Is it possible to create a table with a scrollbar on the right side using only CSS and without any plugins like jQuery? Additionally, I want the table header to remain fixed in place. What steps do I need to take to achieve this functionality? ...

Tips for displaying the webpage background above a specific div by utilizing a differently shaped div

I designed a webpage with a background image. At the top, I placed a div element (let's call it div_1) set to 50% width which creates a horizontal black bar with 60% opacity. Directly above that, towards the left at 50%, I want another div element (di ...

In AngularJS, the execution of a subsequent AJAX call is reliant on the response of a preceding AJAX

Initially, I invoked the userSignupSubmit function. Within this method, another method called mobilenocheckingmethod is called. This method depends on the response from an AJAX call to make another AJAX call, but unfortunately, the second call does not w ...