Struggles with integrating a disappearing navigation bar when scrolling - JavaScript

I've been struggling with a fixed position navbar on my blog and I'm attempting to incorporate basic JS to hide the navbar while scrolling down and have it reappear when scrolling up. You can find the code snippet I'm trying to implement in this fiddle: https://jsfiddle.net/mariusc23/s6mLJ/31/

I've hit a roadblock and encountered some issues that I can't seem to resolve. Could it be related to the responsiveness of my navbar? Any insights or suggestions would be greatly appreciated.

Link to my site

// Hide Header on on scroll down
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();
    
    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;
    
    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('nav-up').addClass('nav-down');
        }
    }
    
    lastScrollTop = st;
}
.nav-up {
  top: -40px;
}
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
  <script src="/javascript/navhider.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<!--NAVBAR-->
<aside id="shadow" class="nav-down">
  <div id="navbar">
    <nav>
      <ul>
        <li class="noselect"><a href="/">Home</a></li>
        <li class="noselect"><a class="navlink" href="{{ "/contact" | prepend: site.baseurl }}">Contact</a></li>
        <li class="noselect"><a class="navlink" href="{{ "/portfolio" | prepend: site.baseurl }}">Portfolio</a></li>
        <li class="noselect"><a class="navlink" href="https://github.com/joelbitar1986">Github</a></li>
        <li class="noselect"><a class="navlink" href="{{ "/blog" | prepend: site.baseurl }}">Blog</a></li>
      </ul>
      <div class="handle"><a id="menu-icon">&#9776;</a></div><!--On a mobile device this is the only list item displaying -->
    </nav>
  </div>
</aside>

Answer №1

By incorporating this script into my index.html file, I achieved success in accomplishing my goal. Additionally, I managed to get the original fiddle working by replacing 'header' with 'aside' from my own code. This experience taught me that patience truly pays off!

<script type="text/javascript>

        (function()  {

            var documentElem = $(document),
                aside = $('aside'),
                lastScrollTop = 0;

            documentElem.on('scroll', function() {
                var currentScrollTop = $(this).scrollTop();

                //scroll down
                if (currentScrollTop > lastScrollTop ) aside.addClass('hidden');
                //scroll up
                else aside.removeClass('hidden');

                lastScrollTop = currentScrollTop;

            });

        })();

    </script>

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

Zod: ensure at least one field meets the necessary criteria

Currently, I am in the process of developing a form that allows users to input either their email address or phone number. While they have the option to provide both, they are required to enter both before proceeding. For this project, I am utilizing Zod a ...

Error Message: "Issue with jQuery mobile: Uncaught TypeError - Unable to read property 'abort' of undefined during AJAX request"

Hey there, I recently created a website using jQuery Mobile and implemented the autocomplete feature. However, I encountered an error message saying Cannot read property 'abort' of undefined. Here is the code snippet: <div id="myPage"> ...

Automatically open the first panel of the Jquery Accordion

Is there a way to automatically have the first panel in my JQuery accordion open when all panels are initially closed? Here is the HTML code for my accordion: <div class="accordionx"> <div class="acitemx"> <h3>First Panel</h3> ...

What is the best way to update the wrapper when the iframe URL is modified?

On my webpage, there is an iframe that contains a form. I have a banner or header visible on the page as well. Once the user submits the form within the iframe, I would like the banner to disappear. To see an example of what I mean, you can visit This pa ...

Dynamic v-model for a group in Vue2

I am currently working on a housing form and I have encountered a roadblock that I need assistance with. Essentially, when a user selects that their house has 2 floors in the form, they are then prompted to input the number of rooms, toilets, balconies, et ...

JavaScript technique for dynamically clicking an 'a href link'

Similar Question: Is it possible to simulate a click event on a link or element using JavaScript? How can I programmatically click an anchor (href) link using JavaScript? I have the following code to trigger JavaScript functionality when the link is cl ...

Utilizing Sharepoint - accessing the Sp.Web.currentUser Property

I'm diving into a website I've been tasked to explore. While my HTML skills are limited, I'm eager to retrieve some SharePoint information using JavaScript. I launched my console and experimented with: var value = SP.Web.get_currentUser();, ...

Avoiding state transitions within Angular's ui-router from within a directive

One of the challenges I am facing involves a directive called clickable-tag, where I pass my data as the tag's name (tag.tag): <a class="item item-avatar" ui-sref="nebula.questionData({questionId: question.id})" ng-repeat="question in questi ...

Overlapping floating action buttons

I am trying to display two floating action buttons (FABs) on top of each other, but currently they are overlapping as shown in the picture below. Although I know this may be a common issue, I have not been able to find a solution using Vuetify. https://i ...

Controlling checkboxes generated by jQuery using C#

Here is the issue I am currently facing: I am trying to control the state of a checkbox on a webform page using Visual Studio 2010. I have simplified the code to help explain my problem more clearly. To dynamically retrieve the state of my checkbox, I ha ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

What is the best way to select and style individual HTML elements using CSS?

Having trouble editing a Validations Form in Ionic 4 with CSS. It seems that only the form elements are targeted after clicking on the form group. Attached below are the form states before and after click. I'm unable to style the form elements before ...

ng-admin fails to identify custom field view

I've been exploring ng-admin. After referring to the documentation, I decided to create a custom field. However, even though ng-admin recognizes the FooFieldType, it is not rendering the FoofieldView and instead using the original FieldView! Conf ...

What is causing my Angularjs View to not update upon clicking, even though I am successfully retrieving the content?

<div class="example" ng-controller="Ctrl"> <div ng-repeat="item in items"> <button ng-click="removeItem(item.id);">remove</button> <div class="element" id="{{itemId}}"></div> </div> <div> var a ...

Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifyin ...

"Utilizing multiple materials in a single obj file using the power of three.js

As I work with three.js to load an obj file featuring a ring adorned with pearls, I face a challenge. The obj file lacks an mtl file, a result of the exporting software - possibly Rhinoceros - not including it (as per the graphic designer's explanatio ...

NVD3 struggling with handling oversized data

I am facing a major issue with the implementation of a graph using NVD3. It appears that NVD3 struggles to handle datasets containing large values. The graph in question can be viewed at: . The code snippet for the graph is provided below: nv.addGraph(fun ...

Securely Saving JWT Tokens from Auth0 Login in Node.js Express

As a novice in the world of Auth0, I am currently working on integrating it into my regular express web application. My main goal is to secure and validate users before they are able to access certain endpoints. From what I have gathered, this can be achie ...

My attempts to connect to the FreeSwitch server and make calls to the SIP client (XLite) using the SIPml5 client have been met with challenges

I am encountering issues with registering to a FreeSwitch server and making calls to a SIP client (XLite) using the SIPml5 SIP client. Below is the HTML5 code I am using: <!DOCTYPE html> <html> <head> <meta content="charset=utf-8"/ ...

Ways to send information to browser javascript from Spring MVC controller

Looking for the most efficient method to transfer data from Spring MVC to JavaScript. Let's say there is an array in JavaScript: var myArray = new Array(); And in the Java backend, there is another array: int[] myArray = new int[100]; What would ...