I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I start scrolling. After that initial glitch, everything works as intended.

Is there a way to make sure the navigation bar stays hidden when the page is refreshed?

Below is the JavaScript code I am using:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">
      $(document).ready(function(){$(window).scroll(function(){
            if( $(this).scrollTop() > 4000){
              $('#navigation').fadeIn( "slow", "linear" )
            } else {
              $('#navigation').fadeOut( "slow", "linear" )
            }
          })
        })
     </script>

And here is the CSS code for styling the navigation bar:

nav ul {
        position:fixed;
        list-style: none;
        width: 1100px;
        height: 40px;
        margin: 30px 222px auto;
        padding: 20px 20px 20px 20px;
        background-color: #798c39;
        text-align: center;
        }

Answer №1

Consider exploring an alternative approach. Rather than relying solely on jQuery, I suggest leveraging pure JavaScript and CSS for better performance and effectiveness.

const nav = document.querySelector('#navigation');

function showNav(){
    nav.classList.add('show');
}

function hidewNav(){
    nav.classList.remove('show');
}
var currPos = window.scrollY;
document.addEventListener('scroll', () => {
  if (window.scrollY < currPos) {
  //scroll up
    hidewNav();
  } else {
  //scroll down
    showNav();
  }
  currPos = window.scrollY;
});
body {
  margin: 0;
  height: 2000px;
  margin-top: 100px;
}

nav {
  position: fixed;
  list-style: none;
  width: 100%;
  height: 70px;
  top: 0;
  margin: 0;
  background-color: #798c39;
  text-align: center;
  transform: translateY(-100px);
  transition: 0.3s;
}

.show {
  transform: translateY(0);
}
<html>
  <head>

  </head>
  <body>
    <header>
      <nav id="navigation">
        <ul>

        </ul>
      </nav>
    </header>
    <main>
   
    </main>
  </body>
</html>

Answer №2

Whether the space in the navbar is reserved or not on load will determine the outcome.

Based on the JavaScript provided, it seems likely that the space is reserved, so you should ensure it starts with opacity: 0.

To make this adjustment in your code, simply add the following to your stylesheet:

nav {
  opacity: 0;
}

If the fadeIn/fadeOut keyframes impact dimensions as well as opacity, those changes will need to be considered. Feel free to share the keyframes for further assistance.

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

retrieve a reply from a PHP script and incorporate it into JavaScript following an AJAX request

I've been working with an ajax call and everything seems to be running smoothly thanks to this script: $(document).ready(function() { $('.sortable').sortable({ stop: function(event, ui) { $(ui.item).effect("highlight"); ...

Unexplained disappearance of div element in Vue Router's Navbar

I have been working on integrating a Vue Router into my navbar and everything seemed to be going well. You can check out the code here. The navigation menu I created works perfectly, allowing users to navigate between the home template and about template w ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...

What is the best way to make an element "jump to the top" when the parent element has reached its maximum height?

I have a parent div containing 6 child divs. The height of the internal divs changes dynamically based on the data. The outer div has a fixed height set. I want the internal divs to move to a new column inside the parent div when they no longer fit in term ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

What is the process for incorporating a custom type into Next.js's NextApiRequest object?

I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error. Below is my code snippet: import { verifyJwtToken } from "../utils/verifyJwtToken.js"; imp ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

Choosing Elements from Twin Dropdown Lists in PHP

I am currently working on building a dynamic drop-down menu where the options in the second dropdown depend on the selection made in the first one. The initial dropdown consists of a list of tables, and based on which table is chosen, the columns of that s ...

What is the proper sequence for binding jQuery to elements?

I'm currently facing a challenge with using jQuery to link a function to an element. Essentially, I'm loading a series of divs via JSON, with each item in the JSON having an "action" assigned to it that determines which function should be trigger ...

Passing an event from a Vue3 parent component to its child component

How do I trigger a load event from a parent component to the child component? The child component needs to be able to listen for the load event in a slot-defined element and then perform some actions with the event. For example: <template> <slot ...

Button component in React remains visible until interacted with

https://i.stack.imgur.com/gTKzT.png I'm dealing with a sign out component in my app that requires me to click on it specifically to unselect any part of the application. This is implemented using React Material UI. <MenuItem onClick={e => this ...

Ensure that the innerHTML of the span tag does not contain line breaks

Is there a way to prevent the span tag inside the div with the item class innerHTML from causing a line break, regardless of its length? I also need to ensure that any innerHTML exceeding the item width does not overlap but is hidden. I have attempted usin ...

Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;? However, if I use bracket notation like return contacts[i][prop];, it works fine an ...

Launching JQuery modal upon button click

I'm encountering an issue with jQuery Mobile. Here is the JSFiddle link: http://jsfiddle.net/Gc7mR/3/ Initially, I have a Panel containing multiple buttons. The crucial button has an id of 'define'. <div data-role=header data-position= ...

React-router causing issues with Redux integration

Currently, I'm utilizing the following libraries: react v16.2.0, react-redux v5.0.7, react-router-dom v4.2.2, redux v3.7.2 The main goal is to update some properties within the Auth component and have these changes reflected when the user visits the ...

Managing changes to object properties in Angular

I am encountering a situation where I have an object containing both an 'id' and 'name' property, structured like this: function format(id){ return '(' + id + ')'; } function MyObject(id){ this.id = id; this. ...

Are there any public APIs available for testing JSONP AJAX calls?

Does anyone know of any public web API, aside from Twitter, that I can experiment with by making an ajax call using the jsonp protocol? ...

Steps for Loading HTML5 Video Element in Ionic 2

Struggling to showcase a list of videos from my server, here's the issue I'm encountering and the layout of the app. https://i.stack.imgur.com/HWVt3.png This is the code snippet in HTML: <ion-list> <button ion-item *ngFor="let v ...

When utilizing jQuery.Mockjax to simulate the JSON data, the Backbone.Collection.fetch() function consistently results in a 404 error

My setup is pretty straightforward: Main.js: (function($) { "use strict"; var Company = Backbone.Model.extend({ defaults: { title: "", description: "" }, initialize: function() { ...