The navigation bar becomes sticky and covers up the content as you scroll back to the

Issue with sticky navbar: The first home div displays correctly when the page loads. However, upon scrolling down and then back up, some content from the home div gets hidden behind the sticky nav bar at the top. How can this behavior be fixed? Looking for any suggestions!

window.onscroll = () => {
  myFunction()
};

const navbar = document.getElementById("navbar");

const sticky = navbar.offsetTop;

myFunction = () => {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
body {
  padding: 0px;
  margin: 0px;
}

#navbar {
  overflow: hidden;
  background-color: #000;
}

#navbar a {
  float: right;
  display: block;
  text-align: center;
  padding: 1vw;
  text-decoration: none;
  font-family: 'Muli', sans-serif;
  font-size: 2.5vw;
  font-weight: 400;
  font-style: italic;
}

.color-nav a {
  color: white;
}

.active {
  background-color: #fff;
  color: black !important;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.main-section {
  height: 45vw;
}
<body>
  <header>
    <nav>
      <div class='color-nav' id="navbar">
        <a id='contact-link' href="#contact">Contact</a>
        <a id="about-link" href="#about">About</a>
        <a id='portfolio-link' href="#portfolio">Portfolio</a>
        <a id='home-link' class="active" href="#home">Home</a>
      </div>
    </nav>
  </header>
  <section>
    <div id='home-1' class="home main-section">
    </div>
  </section>
  <section>
    <div id="portfolio-1" class="portfolio main-section">

    </div>
  </section>
  <section>
    <div id="about-1" class='about main-section'>

    </div>
  </section>
  <section>
    <div id='contact-1' class='contact main-section'>

    </div>
  </section>

</body>

Answer №1

When scrolling, the issue arises when you apply the 'fixed' position to the #navbar element. This action removes it from the natural flow of the page and fixes it to the screen. Consequently, the <nav> and <header> elements lose their height and collapse to 0. Inspecting the #navbar in Chrome dev tools reveals that it is 31px tall (may vary based on window size due to padding set in vw units). To resolve this, consider assigning a fixed height to either the parent <header> or <nav> element matching the navbar's height.

header{
  height:31px;
}

Here is an example snippet:

window.onscroll = () => {
  myFunction()
};

const navbar = document.getElementById("navbar");

const sticky = navbar.offsetTop;

myFunction = () => {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
body {
  padding: 0px;
  margin: 0px;
}

header{
  height:31px;
}

#navbar {
  overflow: hidden;
  background-color: #000;
}

#navbar a {
  float: right;
  display: block;
  text-align: center;
  padding: 1vw;
  text-decoration: none;
  font-family: 'Muli', sans-serif;
  font-size: 2.5vw;
  font-weight: 400;
  font-style: italic;
}

.color-nav a {
  color: white;
}

.active {
  background-color: #fff;
  color: black !important;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

section{
  height:100vh;
  border:5px solid green;
}
  <header>
    <nav>
      <div class='color-nav' id="navbar">
        <a id='contact-link' href="#contact">Contact</a>
        <a id="about-link" href="#about">About</a>
        <a id='portfolio-link' href="#portfolio">Portfolio</a>
        <a id='home-link' class="active" href="#home">Home</a>
      </div>
    </nav>
  </header>
  <section>
    <div id='home-1' class="home main-section">
    </div>
  </section>
  <section>
    <div id="portfolio-1" class="portfolio main-section">

    </div>
  </section>
  <section>
    <div id="about-1" class='about main-section'>

    </div>
  </section>
  <section>
    <div id='contact-1' class='contact main-section'>

    </div>
  </section>

If your navbar will always be at the top of the page, there is no need for JavaScript events related to scrolling. Simply add padding to the body and set the navbar position to fixed. These scroll events are necessary only if you want the navbar to fix after scrolling past a certain point. Here is an example without such events:

body {
  padding: 0px;
  padding-top:31px;
  margin: 0px;
}
nav{
  position:fixed;
  top:0;
  width:100%;
}

#navbar {
  overflow: hidden;
  background-color: #000;
}

#navbar a {
  float: right;
  display: block;
  text-align: center;
  padding: 1vw;
  text-decoration: none;
  font-family: 'Muli', sans-serif;
  font-size: 2.5vw;
  font-weight: 400;
  font-style: italic;
}

.color-nav a {
  color: white;
}

.active {
  background-color: #fff;
  color: black !important;
}

section{
  height:100vh;
  border:5px solid green;
}
  <nav>
    <div class='color-nav' id="navbar">
      <a id='contact-link' href="#contact">Contact</a>
      <a id="about-link" href="#about">About</a>
      <a id='portfolio-link' href="#portfolio">Portfolio</a>
      <a id='home-link' class="active" href="#home">Home</a>
    </div>
  </nav>

  <section>
    <div id='home-1' class="home main-section">
    </div>
  </section>
  <section>
    <div id="portfolio-1" class="portfolio main-section">

    </div>
  </section>
  <section>
    <div id="about-1" class='about main-section'>

    </div>
  </section>
  <section>
    <div id='contact-1' class='contact main-section'>

    </div>
  </section>

Answer №2

position: absolute;  

By using absolute positioning, you can ensure that the element doesn't leave a gap and the space it occupies will not be taken by other elements due to relative behavior. To position the content correctly, you may need to adjust the margin or padding to account for the size of the navigation height.

Answer №3

To resolve the issue where the class was not being removed upon scrolling to the top, I updated window.pageYOffset >= sticky to window.pageYOffset > sticky.

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

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...

How can I establish the conversion from pixels to em units?

According to a source I found, 1 em is equivalent to 16px. You can read more about it here. Despite setting the font-size to 100% in the body and using font-size: 1em, the standard font size in my Jekyll site remains 12px. Curious? Visit my Jekyll site a ...

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

When floating a heading 4 (h4) and two divs to the left, and a single div to the right,

When floating a h4 and 2 divs to the left, and another div to the right, how can I place a block inside the remaining space that perfectly fills it? The background color of this space should not spread outside. [h4][div][div][remaining space][div] Thank ...

Mobile WEBSITE Development with Ionic Framework

Exploring the potential of utilizing the Ionic Framework for my mobile website has piqued my curiosity. Are there any concerns I should be aware of when running Ionic Framework on mobile browsers? My plan is to leverage the framework's CSS and JS capa ...

Three.JS 3D Model successfully integrated but appears to be invisible on the screen

I've been trying to incorporate a 3D model into my website using three.js, but I've run into an issue. Despite loading the MTL and OBJ files successfully according to the network tab in developer tools, the 3D model remains invisible on the page. ...

Retrieving child component's data property in Vue 3 using TypeScript and Composition API

I have set up two components: a parent and a child. App.vue //Parent <template> <div class="common-layout"> <Container> <Header><center>Vue JS 3 (Composition API and )</center></Header> ...

Converting complex mongodb data structures into Backbone.js Models/Collections

Within my mongodb database, I store collections comprising of documents and embedded documents at the posts and comments levels. One example is a post document that includes two comments as embedded documents. { "__v" : 0, "_id" : ObjectId("502d7b ...

The error message "Angular formGroup requires a FormGroup instance. Kindly provide one."

I used angular reactiveforms to create a form. The default data is successfully printed on the form, however, I am facing an error in the console that says "formGroup expects a FormGroup instance. Please pass one in." Can someone guide me on how to resolve ...

Bug with IE lookahead in Regular Expressions

Currently, I am struggling to define the regular expression needed for proper validation in my ASP.NET validator. Although it works fine in Firefox, the sample string is not validating correctly in IE using the following expression: 12{2}12{0-9}1{12,13} ...

Navigate down to the bottom of the element located on the webpage

I'm trying to create a feature where clicking an anchor tag will smoothly scroll to a specific element on the page. Currently, I am using jquery scrollTo for this purpose. Here's the code snippet: $.scrollTo( this.hash, 1500, { easing:&apos ...

Utilizing JQuery Mobile AJAX to load JSON data

Hey there, I'm currently diving into the world of developing my first mobile app for my WordPress blog. One of the key components I've set up is the JSON API plugin on my WordPress site, allowing me to access my JSON Data via "example.com/api/get ...

Can I use Mongoose to apply a filter to this request?

I have a requirement to query all products with the category status set to true. My product model looks like this: const ProductSchema = Schema({ name : {type: String}, category: {type: Schema.Types.ObjectId, ref: 'Category'} }) Normally, I wou ...

Creating a CSS binding for width: a step-by-step guide

I have a complex layout with multiple elements in different divs that need to be aligned. Hardcoding the width or using JS on page load to specify values in pixels both seem like messy solutions. How can I achieve this without causing a zigzag effect? Her ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

How can I eliminate the border appearance from a textfield fieldset component in Material-UI?

I have been struggling to remove the border using CSS code I found on Stack Overflow, but unfortunately, the issue persists. If anyone could kindly assist me in fixing this problem, I would be extremely grateful. Can someone please advise me on the specif ...

There was a syntax error when trying to include HTML code and JavaScript actions within a PHP file

My current challenge involves loading dataTables using AJAX in Laravel framework. Here is a snippet of my code: if($posts) { foreach($posts as $r) { $nestedData['name'] = $r->name; $nestedData['email'] = $r->e ...

Locate grandchildren elements using getElementById

My task is to modify the content and attributes of the table. The DOM structure is generated by a third-party tool, and I am using JavaScript to make changes in various sections. <div id="myId"> <div> <div> <table&g ...

Tips for evaluating the performance of webGL clients using three.js

Currently, I am working on a graphic project utilizing three.JS and I am interested in automatically assessing the GPU performance of my client's device. This will help me determine the optimal number of elements to load in the application. Essentiall ...

An AJAX event handling function returns a null value upon invocation

Recently, I've been working on a function named 'getAuthor' which includes an AJAX event. Here's the code snippet: function getAuthor(id){ $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){ ...