Can someone explain the method for displaying or concealing a menu based on scrolling direction?

https://i.stack.imgur.com/tpDx0.jpg I want to hide this menu when scrolling down and show it when scrolling up.

The code for my menu bot is:

<script>
            var previousScroll = 0;
            $(window).scroll(function(event){
               var scroll = $(this).scrollTop();
               if (scroll > previousScroll){
                   $("menu-footer").filter(':not(:animated)').slideUp();
               } else {
                  $("menu-footer").filter(':not(:animated)').slideDown();
               }
               previousScroll = scroll;
            });
    </script>

    <section id="menu-footer">
        <ul>
            <li>
                <li><a href="javascript:history.back()"><i class="fa fa-arrow-circle-left"></i><?php _e("Back", ET_DOMAIN); ?></a></li>
            </li>
            <li>
                <a class="<?php echo $nearby_active; ?>" href="#" id="search-nearby"><i class="fa fa-compass"></i><?php _e("Nearby", ET_DOMAIN); ?></a>
                <form id="nearby" action="<?php echo get_post_type_archive_link('place')  ?>" method="get" >
                    <input type="hidden" name="center" id="center_nearby" />
                </form>
            </li>
            <!--<li><a href="#"><i class="fa fa-plus"></i>Submit</a></li>-->
            <!--<li>
                <a class="<?php echo $review_active; ?>" href="<?php echo et_get_page_link('list-reviews') ?>">
                    <i class="fa fa-comment"></i><?php _e("Reviews", ET_DOMAIN); ?>
                </a>
            </li>-->
            <li><a class="<?php echo $post-place; ?>" href="<?php echo et_get_page_link('post-place')?>"><i class="fa fa-flag-checkered"></i><?php _e("Post an Ad", ET_DOMAIN); ?></a></li>
            <?php if(has_nav_menu('et_mobile_header')) { ?>
            <li>
                <li><a href="#" class="search-btn"><i class="fa fa-search-plus"></i><?php _e("Search",...

<p> The above script has been implemented to hide the menu.
My CSS for menu-footer is:</p>

<pre><code>#menu-footer {
    width: 100%;
    background: #5f6f81;
    position: fixed;
    bottom: 0;
    transition: top 0.2s ease-in-out;
    z-index: 100
}

What am I doing wrong in getting this script to function correctly? Any alternative solution would be appreciated.

Answer №1

This initial example was created using plain JavaScript to make it easily understandable at a glance in the code. It involves hiding the menu by adjusting the 'bottom' attribute of the CSS style (from 0 to -100) based on the position of the scrollbar (when the scrollbar is more than 0 pixels from the top). The menu reappears (from -100 to 0) when the scrollbar returns to the top (0px), with a CSS transition effect animating the change:

window.addEventListener("scroll", bringmenu);

function bringmenu() {
    if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
        document.getElementById("bottommenu").style.bottom = "-100%";
    } else {
        document.getElementById("bottommenu").style.bottom = "0";
    }
}
body {
  margin: 0;
  background: lavender;
}

#bottommenu {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: auto;
  background: tomato;  
  -webkit-transition: bottom 2s;
  transition: bottom 2s;
}
<div id=content>
<p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p>
</div>

<div id=bottommenu>
<span>bottom </span><span>bottom </span><span>bottom </span><span>bottom </span><br><span>bottom </span><span>bottom </span><span>bottom </span><span>bottom </span>
</div>

Update: Responding to requests in the comments, this second snippet toggles the menu when scrolling up or down, irrespective of the current position of the scrollbar (to determine the direction, it compares the current position with the previous one and then stores the current position in a variable for comparison in the next scroll event):

var lastScrollTop = 0;

window.addEventListener("scroll", function(){  
   var st = window.pageYOffset || document.documentElement.scrollTop;  
   if (st > lastScrollTop){
       document.getElementById("bottommenu").style.bottom = "-100%";
   } else {
      document.getElementById("bottommenu").style.bottom = "0";
   }
   lastScrollTop = st;
}, false);
body {
  margin: 0;
  background: honeydew;
}

#bottommenu {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: auto;
  background: hotpink;  
  -webkit-transition: bottom 2s;
  transition: bottom 2s;
}
<div id=content>
<p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p>
</div>

<div id=bottommenu>
<span>bottom </span><span>bottom </span><span>bottom </span><span>bottom </span><br><span>bottom </span><span>bottom </span><span>bottom </span><span>bottom </span>
</div>

scroll direction code by @Prateek

Answer №2

Essentially, there are 3 key concepts you need to implement in order to achieve this effect.

  1. Make the menu/header fixed.
  2. Apply a class to hide the header/menu when scrolling down.
  3. Remove the class to reveal the header/menu when scrolling up.

Check out a live demo created by Marius Craciunoiu for reference.

Here is the HTML code snippet:

<header class="nav-down">
    This is your menu.
</header>
<main>
    This is your body.
</main>
<footer>
    This is your footer.
</footer>

Javascript code snippet:

// Javascript functionality to toggle header visibility on scroll
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Ensure sufficient scroll distance
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // Add or remove class based on scroll direction and position
    if (st > lastScrollTop && st > navbarHeight){
        // Scrolling Down
        $('header').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scrolling Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('nav-up').addClass('nav-down');
        }
    }

    lastScrollTop = st;
}

CSS code snippet:

   body {
    padding-top: 40px;
}

header {
    background: #f5b335;
    height: 40px;
    position: fixed;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
}

.nav-up {
    top: -40px;
}

main {
   background:url(
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAPklEQVQYV2O8dOnSfwYg0NPTYwTRuAAj0QqxmYBNM1briFaIzRbi3UiRZ75uNgUHGbfvabgfsHqGaIXYPAMAD8wgC/DOrZ4AAAAASUVORK5CYII=
   ) repeat;
    height: 2000px;
}

footer { background: #ddd;}
* { color: transparent}

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

Calls to debounced functions are postponed, with all of them running once the waiting timer is complete

Utilizing the debounce function to create a real-time search feature. Researching more on debouncing from https://css-tricks.com/debouncing-throttling-explained-examples/, it seems like the function should control the number of calls made. In my scenario ...

The anchorEl state in Material UI Popper is having trouble updating

I am currently facing an issue with the Material UI popper as the anchorEl state remains stuck at null. Although Material UI provides an example using a functional component, I am working with a class-based component where the logic is quite similar. I w ...

The mysterious behavior of CSS3 transforms on intricate rotations

When a div is viewed in perspective and has the transformations rotateY(-90deg) rotateX(-180deg), adding rotateZ(-90deg) to it results in a rotation of +270 degrees instead of -90 degrees. The new style of the div changes from transform: rotateY(-90deg) ...

Reproducing scripts in Google Tag Manager and React/Next applications

Currently, I am delving into the realm of Google Tag Manager and React + Next.js for the first time. This experience is proving to be quite intriguing as my familiarity with GTM is limited and my exposure to React is even less. Nonetheless, it's not a ...

Exploring the Power of ColdFusion 9, JSON, and Embracing jQuery Easy

I am attempting to convert a ColdFusion query into JSON format in order to use it with jQuery EasyUI, specifically with a Datagrid. The required format for EasyUI based on their example .json files is as follows: {"total":2 , "rows":[ { "p ...

Angular allows for the creation of a unique webpage layout featuring 6 divs

I am working on a project where I have an image of a car and I need to overlay 6 divs onto the image which can be selected with a mouse click. When a user clicks on one of the divs, it should change color. I've attempted using z-index, but it doesn&ap ...

Exploring the option of eliminating the email field from the PHP redirect function and transforming it into a pop-up notification

I am currently utilizing the following code to send an email notification to my address whenever a new user signs up: <?php $errors = ''; $myemail = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0ded1ddd ...

Guide to exporting several Chart.JS graphs to a PDF document with each graph on a separate page

I am currently utilizing the JavaScript code provided below to generate a pdf file containing multiple charts. However, all the charts are being placed on a single page. My inquiry is regarding how I can customize the code to have each chart on its own sep ...

Retrieve the stylesheets located within the <head> section of an external webpage and load them onto the current page

Trying to figure out a solution, I received an interesting request from a friend. They asked for help in creating a webpage that can dynamically pull a div tag from an external page (on a different server). To accomplish this, I utilized jquery's .loa ...

Displaying a separate page upon clicking the add button in jqGrid: Tips and Tricks

I am a beginner when it comes to MVC, jQuery, and jqGrid. I have been struggling for the past couple of days trying to figure out how to redirect to another page when the user clicks the add button. Additionally, I need to perform the same action when the ...

The HtmlHelper ActionLink consistently establishes the current controller instead of allowing for the specification of another controller

I have been utilizing the HtmlHelper class to incorporate some code into my layout Navbar as a menu. Here is the code snippet: public static MvcHtmlString MenuLink(this HtmlHelper helper,string text, string action, string controller) { ...

Challenge with Filter Functionality when Activating Button

Can you help me implement a search filter using buttons with the Isotope Plugin? For example, entering a search value in an input field and then clicking a search button to display the search results. How can I achieve this using buttons? Below is the H ...

Issue with animation transition not triggering on initial click

I am currently working on creating an animation for a form using JS and CSS. Here is the code snippet I have: var userInput = document.getElementById("login-user"); var userLabel = document.getElementById("user-label"); // User Label Functions funct ...

What could be the reason for the sudden lack of content from the Blogger API?

For weeks, I've been using the Google API to retrieve JSON data from my Blogger account and showcase and style blog posts on my personal website. Everything was functioning flawlessly until yesterday when, out of the blue, the content section stopped ...

Error Unhandled in Node.js Application

I have encountered an issue in my NodeJS application where I have unhandled code in the data layer connecting to the database. I deliberately generate an error in the code but do not catch it. Here is an example: AdminRoleData.prototype.getRoleByRoleId = ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Enable strict mode for older web browsers

I would like to incorporate the "use strict"; statement into my function, but unfortunately it is not compatible with older browsers such as ie7 and ie8. Is there a workaround to ensure this functionality works in legacy browsers? Could someone please cla ...

Enhancing the appearance of the MUI DatePicker

I'm currently using a DatePicker component from Mui Lab and I'm attempting to customize the appearance of the Calendar component by incorporating some border or background color. Although I've tried utilizing the PaperProps prop for DatePick ...

Error: Type Error when using custom App and getInitialProps in Next.js

I have a simple app built using the Next JS starter kit, and I am attempting to integrate custom functionality as outlined in the documentation: class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {}; ...