Code to conceal navigation bar...positioned neither at the top nor at the bottom of the scroll

As a graphic designer with some coding knowledge, I'm struggling with a particular issue...

I have a traditional navigation bar that only appears when the user scrolls down a bit, which I achieved through JavaScript. However, I want this to occur only in the middle of each page - around 100px from the top and 100px from the bottom of the scroll. This is because I already have breadcrumbs at the top and a footer at the bottom, making the navigation bar unnecessary in those areas.

I've attempted to combine the navbar with scroll detectors or read scroll position bars, but I haven't been able to make anything work...

Any assistance would be greatly appreciated!

Here is my current code for the navbar (suggestions for improvements are also welcome):

    var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.bottom = "0";
  } else {
    document.getElementById("navbar").style.bottom = "-100px";
  }
  prevScrollpos = currentScrollPos;
}

Answer №1

If my understanding is correct, I think you are looking for something along these lines:

    window.onscroll = () => { 
        const scrollPosition = window.scrollY; 
        const offsetRequired = 100; 
        const targetElement = document.body; //Adjust as needed
        if(scrollPosition > offsetRequired && (targetElement.scrollHeight - window.innerHeight - scrollY) > offsetRequired )
            console.log('shownavbar')
        else
            console.log('hidenavbar')
    }

Answer №2

With guidance from @NourAshraf, I made some tweaks to the existing code and now it's working perfectly!

For those who may find it helpful, here's a simplified version. To make it easier to understand, I changed the body color to green when the navigation bar should be visible and red when it shouldn't.

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  var offset = 500; const targetEl = document.body; //Adjust as needed

  if (prevScrollpos > currentScrollPos && currentScrollPos > offset && (targetEl.scrollHeight - window.innerHeight - scrollY) > offset) {
    document.body.style.backgroundColor = "green";
  } else {
    document.body.style.backgroundColor = "red";
  }
  prevScrollpos = currentScrollPos;
}

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

The jquery autocomplete feature is failing to display search results

I have a text input with autocomplete functionality using JavaScript: JavaScript code: $("#descSearchBox").keyup(function(e) { $(".ui-autocomplete").removeClass("ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all") .ad ...

One class seems to be causing issues with hover functionality while the other works perfectly fine

HTML: <div class="channellist"></div> Through the use of Ajax, I am able to dynamically retrieve channels when the page loads and then append them within the channellist container. Once appended, my HTML structure appears as follows: <div ...

"Unlocking the power of Webdriver.io: Sending information to a personalized reporting system

Utilizing the wdio tool provided by the webdriver.io npm package is how I execute Mocha test-cases. The snippet below showcases a segment of the wdio.conf.js file: var htmlReporter = require('./js/reporter/htmlReporter'); htmlReporter.reporterN ...

What occurs when a file being imported is also importing a file that the first file is already importing?

I have three JavaScript files with dependencies: - main.js <- dependencies: module.js, helper.js - module.js <- dependencies: helper.js - helper.js <- no dependencies main.js and module.js both import from helper.js, while main.js imports from ...

Tips for resolving the error "Binding element has no default value and initializer provides no value in TypeScript"

I am currently in the process of converting a JavaScript Apollo GraphQL API project to TypeScript. During this migration, I encountered an error related to a user code block: var idArg: any Initializer provides no value for this binding element and the ...

Mongodb: Search for IDs within a nested array field

My MongoDB data structure includes user profiles with friend request information. Here's an example: { _id: "someId", profile: { username: "oliv", friendRequests: [ { fromUserId: "anId", accepted: false, created: " ...

Apollo's MockedProvider failing to provide the correct data as expected

I created a function called useDecider that utilizes apollo's useQuery method. Here is the code: useDecider: import { useState } from 'react'; import { useQuery, gql } from '@apollo/client'; export const GET_DECIDER = gql` quer ...

The server is currently pointing towards my local C drive directory instead of the desired message location

My goal is to create a functionality where, upon clicking the calculate button (without performing any calculations yet), the user will be redirected to a new screen displaying a response message that says "Thanks for posting that!". However, instead of th ...

Magento issue with unresponsive image map functionality

My website is built using the Ultimo theme in Magento, and I have implemented a script from to make the image map responsive. Here is the HTML code: <img name="sale" src="sale_1.jpg" width="1180" height="200" id="sale" usemap="#m_sale" alt="" />< ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

Having difficulties fetching images from the Twitter API

I'm encountering an issue with a simple Twitter API request for a specific tweet. Although the tweet should have multiple images attached to it, the media entity object is returning empty. Here's the tweet in question: https://twitter.com/talonc ...

Text area capacity

Is there a limit to the maximum capacity of a textarea for accepting text? The HTML page functions correctly when the text is limited to around 130-140 words. However, if the text exceeds this limit, it causes the page to hang without any response. The tex ...

How can one determine the completion of a chunked download request in Angular's HTTP client?

Currently, I am utilizing angular's HttpClient to retrieve an arraybuffer. The server is transmitting the data along with the following headers: *To avoid any confusion, the download route essentially retrieves a chunk file stored in the cloud. Howev ...

The Sacred Chalice Trio Vertical Stretch Design

Recently, I've been working on creating a three column layout with percentage width. I stumbled upon the concept of the Holy Grail web design through some online articles and resources. To implement this layout, I referred to an example from The Perfe ...

The Vue component fails to refresh when the state in the store undergoes changes

Trying to create a simple todo list in Vue, but aiming to abstract everything out and utilize a dummy REST API for practice with production-level Vue projects has left my head spinning. While GET, PUT, and POST requests appear to be functioning properly, I ...

Transferring an image file from PHP to JavaScript

I have encountered an issue with transferring images stored as LONGBLOB files in my database to a JS file for dimension comparison with the screen. Here is how I retrieve the images: function fillArrays(){ $idArray = array(); $sql = "SELECT oglas_id,s ...

Is it possible to manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

Send the data to be placed in the div to launch the window

I'm attempting to open a new window within the same tab and transfer some html code to be inserted into a specific div section of the newly opened window. However, I'm encountering difficulties in passing the data as illustrated below: JavaScrip ...

Shuffle the setInterval function: How to consistently rewrite with random intervals?

Seeking guidance on how to implement the following task: generate a random number after a random amount of time and then reuse it. function doSomething(){ // ... do something..... } var rand = 300; // initial random time i = setInterval(function(){ ...

Recognizing the click event on the checkbox within a <TableRow/> in ReactJS with MaterialUI

Using ReactJS and MaterialUI's component for tables, I have successfully created a table with two rows, each containing a checkbox. Now, the challenge is to create a method that can recognize when a checkbox is clicked and provide information about th ...