Conceal the navigation bar when scrolling to the top of the

Hey there! I'm looking for a way to hide my navigation bar when not scrolling, and then display it again once I start scrolling. Currently, I have two menus on this website: one with a white background and the other with a blue background.

You can find the menus at

http://dev.thegabrielmethod.com/gabriel/

My goal is to hide the navigation menu items on the white background when the user is not scrolling, and then reveal them as soon as they start scrolling down the page.

https://i.sstatic.net/o1k3h.png

I've tried implementing the following code snippet but unfortunately, it's not working properly:

<script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
        var headerTop = $('#header').offset().top;
        var headerBottom = headerTop + 120; // Sub-menu should appear after this distance from top.
        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop(); // Current vertical scroll position from the top
            if (scrollTop > headerBottom) { 
                if (($("#navigation-alongside").is(":visible") === false)) {
                    $('#navigation-alongside').fadeIn('slow');
                }
            } else {
                if ($("#navigation-alongside").is(":visible")) {
                    $('#navigation-alongside').hide();
                }
            }
        });
    });

</script>

If anyone has any advice or suggestions, please feel free to share!

Answer №1

$(document).ready(function() {
  $(window).scroll(function() {
    $(".menu").css({
      'display': 'none'
    });
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
      $(".menu").css({
        'display': 'block'
      });
    }, 100));
  });
});
.menu {
  position: fixed;
  display: block;
  width: 100%;
  height: 150px;
  margin: 0px !important;
  box-shadow: 0 2mm 10px #aaa;
  text-align: center;
}

body {
  padding: 0px !important;
  height: 200vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="menu"><br/>
    <h1>Menu Box</h1>
  </div>

</body>

Here! It will hide the menu while scrolling and show it again when scrolling is completed.

Please let me know if I have misunderstood your question.

Answer №2

Upon reviewing your HTML, I noticed a few issues. Firstly, the margin setting for the blue nav bar - margin-top: 100px; is unnecessary.

Try running the code below:

Open the website, launch the developer tools > console, execute the code below, then scroll the page to see it working correctly.

Simply run the following code upon page load to address the margin issue mentioned earlier.

jQuery('.banner.include-nav').fadeOut();
jQuery('.nav-bar-below.op-page-header.cf').css({'margin':'0px'});
var h = jQuery('.nav-bar-below.op-page-header.cf').height();
jQuery(window).scroll(function () { 
    if(jQuery(window).scrollTop() > h)
    {
        jQuery('.banner.include-nav').fadeIn();
    }
    else 
    {
        jQuery('.banner.include-nav').fadeOut();
    }
})

Before Scrolling

https://i.sstatic.net/wesrK.png

After Scrolling

https://i.sstatic.net/8TDSg.png

Update

Based on your feedback about hiding only the menu and not the logo in white, try the modified code provided below. Follow the same steps as previously mentioned.

jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeOut();
//jQuery('.nav-bar-below.op-page-header.cf').css({'margin':'0px'});
var h = jQuery('.nav-bar-below.op-page-header.cf').height();
jQuery(window).scroll(function () { 
    if(jQuery(window).scrollTop() > h)
    {
        jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeIn();
    }
    else 
    {
        jQuery('.banner.include-nav > .fixed-width.cf > .sixteen.columns').fadeOut();
    }
})

Answer №3

Here is one method to achieve it:

window.onscroll = function(e) {
    const topMenu = document.querySelector('.banner.include-nav');
    const scrollTopAmount = document.body.scrollTop || document.documentElement.scrollTop;

    if (scrollTopAmount !== 0) {
        topMenu.style.display = 'none';
    }
    else {
        topMenu.style.display = 'block';
    }
}

I hope this solution proves useful.

Answer №4

Hopefully, this snippet of code can help resolve the issue you're facing.

jQuery(window).scroll(function (event) {
    var scroll = jQuery(window).scrollTop();
    console.log(scroll);
if(scroll==0){
jQuery('.include-nav').hide();
  jQuery('.nav-bar-below.op-page-header').css('margin-top','0px');
}else{
  jQuery('.include-nav').show();
  jQuery('.nav-bar-below.op-page-header').css('margin-top','100px');
}
});

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

What is the best way to extract a specific object from an array containing multiple objects?

Upon entry, there is an array with various objects. A function is needed to convert this incoming array of objects into a single object. The goal is to bring it to the desired form using the function provided. var array = [ { k1:v1 }, { k2:v2 }, ...

A guide on accessing the value of ng-model in an AngularJS controller

I am facing an issue with a simple view that contains an input text field where the user enters their name. The controller should retrieve this value and assign it to the employeeDescription variable. However, the ng-model value from the input field is not ...

Is locking Node and npm versions necessary for frontend framework projects?

Currently working on frontend projects in React and Vue, I am using specific versions of node and npm. However, with other developers contributing to the repository, how can we ensure that they also use the same versions to create consistent js bundles? ...

Is the array empty once the functions have been executed?

app.post('/api/edit-profile', regularFunctions, async function (req, res) { let email = req.body.email let password_current = req.body.password_current connection.query('SELECT * FROM accounts WHERE id = ?', req.body.id, asy ...

Tips for manipulating bits 52-32 within Javascript code, without utilizing string methods

Here is my functional prototype code that is currently operational: function int2str(int, bits) { const str = int.toString(2); var ret = ''; for (var i = 0; i < (bits - str.length); ++i) { ret += '0'; } re ...

Using JQuery toggleclass to add transitioning effects to a :after element

I'm using the toggleClass function to add the class .expend to a div with an ID of #menu, which increases the height of the menu from 100px to 200px with a smooth transition effect. I also have a pseudo-element #menu:after for aesthetic purposes. My ...

The issue of memory leakage in Three.js

I have come across an unusual memory leak in three.js (r73). Here are the steps to reproduce it: 1) Go to the following link using Google Chrome (version 46.0.2490.80 m) 2) Open DevTools -> Profiles -> Take Heap Snapshot. Check out my screenshot be ...

What provides greater performance benefits?

When considering performance, which option is more advantageous? 1) Loading jQuery externally or 2) Hosting jQuery on our server ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

Easily adding multiple field data with the same field name into a database can be achieved using Mongoose and Node.js (specifically Express

I am new to using nodejs and exploring the creation of a project focused on generating invoices. My goal is to store product information in mongodb utilizing mongoose and express, but I'm unsure of how to proceed. Below is a snippet of my HTML code.. ...

When can you determine if all the ajax requests in a JQuery each loop have finished?

Within my JQuery each loop, I am triggering multiple ajax requests and looking to display a success message once all calls have been completed. Here is my code snippet: $('.container input:checked').each(function() { json_data = $(this).paren ...

Adding a JavaScript script tag within a React app's ComponentDidMount - a guide

I am currently in the process of implementing Google Optimize on my website. I need to include the following script tag within my page: <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.classN ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

Error encountered while trying to run a three.js example with iewebgl

I'm attempting to utilize the iewebgl and encountering difficulties while trying to run an example from three.js, specifically the webgl_loader_obj. Upon execution, I am facing the following error: SCRIPT445: Object doesn't support this action i ...

Selecting radio buttons across multiple div classes

I've been struggling to programmatically select specific radio buttons on a webpage. My goal is to automatically choose the second option in each group of radio buttons, but I'm getting lost in the syntax. Unlike most examples I've found on ...

ClickAwayListener in MUI has the potential to impact all the elements within a popper when attempting

As a new react developer, I have encountered a small problem with my ClickAwayListener. It should close the Popper component when clicking 'x' or outside of it, which it does successfully. However, I have another component inside my Paper, and wi ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

Using AngularJS to handle click events and blur events

I am attempting to dynamically change the class based on user interaction in my code. The class should switch between "large" and "active" depending on whether the input field is filled or not. Please see the modified script below. <div class="snippe ...

Passing values dynamically to a JavaScript function within a Chrome extension using Python at runtime

I have encountered a unique challenge in my automation work, which I detailed in this query It's important to note that I am utilizing Python with Selenium WebDriver As I navigate through a series of changes and obstacles, I find myself exploring th ...