Fixing Sticky Navigation Bar on Scroll (JavaScript, HTML, CSS)

I'm working on this site as a fun side project, but I've hit a roadblock. The sticky nav bar I implemented jumps when the user scrolls down far enough. Despite reading through other discussions, I can't seem to figure out the solution.

I suspect it might be related to padding, but my JavaScript skills are not the best, so there may be errors in that area as well.

This is the JavaScript code I'm using:

var header = document.getElementById("header");
var navbar = document.getElementById("navbar");

var navbarHeight = navbar.offsetHeight;
var headerHeight = header.offsetHeight;

header.style.height = screen.height - navbarHeight;

function initJake() {
  if (window.pageYOffset > headerHeight) {
    navbar.style.position = "fixed";
    navbar.style.top = "0";

  } else {
    navbar.style.position = "relative";
  }
}
window.onscroll = function() {
  initJake()
};

You can view the full example on jsFiddle here: https://jsfiddle.net/jihlenfeldt/435ugdyf/2/

I'm looking for a way to smoothly transition from absolute to fixed positioning without covering text lines. Any advice would be greatly appreciated, as this issue has been quite frustrating for me.

Answer β„–1

Are you looking for something like this?:

let headerElement = document.getElementById("header");
let navbarElement = document.getElementById("navbar");
let contentElement = document.querySelector('#navbar + .content');

let navbarHeightValue = navbarElement.offsetHeight;
let headerHeightValue = headerElement.offsetHeight;

headerElement.style.height = screen.height-navbarHeightValue;

function initializeFunction(){

    if(window.pageYOffset > headerHeightValue){

    navbarElement.style.position = "fixed";
    navbarElement.style.top = "0";
    contentElement.style.padding = '60px 0 0 0';

}
else{

    navbarElement.style.position = "relative";
    contentElement.style.padding = '0 0 0 0';

}

}


function toggleHamburgerMenu() {
  let submenuElement = document.getElementById("submenu");
  if (submenuElement.style.display == "none") {
    submenuElement.style.display = "block";
  } else {
    submenuElement.style.display = "none";
  }
} 



window.onscroll = function() {initializeFunction()};

The problem here is that when your navbar gets a position of "fixed", its height is no longer considered by the DOM as it will be placed on top of everything. To solve this, it's best to give the element after it (in this case, the content) a padding-top equal to the height of the navbar. Instead of using a fixed number for padding, consider using a variable to dynamically get the height of the navbar since it can vary.

Answer β„–2

Your error lies here.

if (window.pageYOffset > headerHeight) {
    navbar.style.position = "fixed";
    navbar.style.top = "0";
  } else {
    navbar.style.position = "relative"; // this is the issue 

  }

The problem is that your navbar has a position of absolute, and when

window.pageYOffset > headerHeight
returns false, you are setting it to relative

#navbar {
  position: absolute;
  bottom: 0;
  width: 100%;
  background-color: #111;
  z-index: 3;
  overflow: hidden;
  height: 20%;
  padding-bottom: 3%;
  display: flex;
  flex-direction: column;
  transition-property: width;
}

That's why there is a bump. Furthermore, the navbar is now fixed, so it does not interfere with other elements. This results in the div being covered by the navbar or moving upwards.

<div class="content">
    <h1>text here</h1>
    <p>text here text here text here text here text here text here text here text here text here text here text here text here </p>
</div>

A possible solution would be to maintain a consistent position. Let's keep it as relative. Then we can add a top margin to the content div when the position is fixed. This will create some space from above. So, the JavaScript will look like this:

var content = document.getElementsByClassName("content")[0];
if (window.pageYOffset > headerHeight) {

    navbar.style.position = "fixed";
    navbar.style.top = "0";
    content.style.marginTop = "115px";
  } else {

    navbar.style.position = "relative";
    content.style.marginTop = "0px";

  }

And maintain relative in the CSS

#navbar {
  position: relative;
...
}

Therefore, your fiddle will look something like this

Answer β„–3

Why is JavaScript always used to modify the appearance of an HTML element?

JavaScript can be used to determine if a header is out of view and, if so, apply a class to the body. By using CSS, you can then adjust the sticky header like this:

$(window).scroll(function(){
  if($(this).scrollTop() > $('#header').outerHeight()){ 
    $('body').addClass('scrolled');
  } else {
    $('body').removeClass('scrolled');
  }
});

And in the CSS file:

#header { position:relative; }
body.scrolled #header { position:fixed; top:0; left:0; width:100%; }
body.scrolled { padding-top:<Enter here Height of Header to prevent jumping> }

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

Is it advisable to include cursor:pointer in the pseudo class :hover?

Which option is better to use? .myclass { cursor: pointer; } or .myclass:hover { cursor: pointer; } Is there a notable difference between the two? ...

Drawer in Material-UI has whitespace remaining at the corners due to its rounded edges

While using the Material UI drawer, I attempted to round the corners using CSS: style={{ borderRadius: "25px", backgroundColor: "red", overflow: "hidden", padding: "300px" }} Although it somewhat works, the corners appear white instea ...

Troubleshooting a problem with the Jquery Quicksearch plugin on constantly changing web

Quicksearch is pretty amazing... but it faces a usability issue that causes strange behavior. Many users hit enter after entering a search query, which reloads the page without any parameters and destroys the queries. Check this out: Adding: $('for ...

Ensure execution post completion of evalAsync process

I am relatively new to working with JavaScript and Angular technology. I have encountered a situation where two separate pieces of code are running in different callbacks, triggered by third-party libraries (specifically Kendo UI library callbacks). One f ...

Input fields that are dynamically generated do not respond to changes made using .click and .blur methods in jQuery CSS

I'm experiencing an issue with a HTML form where a new input field is generated when a button is clicked, but the dynamically created field is not styled properly. Below is the HTML form code: <form id="form"> <input type="text" id="ent ...

Rewrite the nginx configuration to eliminate the "/index.html" part of the URL while preserving the query

My Nginx configuration specifies index index.html as the default index page. When accessing it as a progressive web app (using Angular), the URL loads as /index.html#/route instead of /#/route for some reason. I want to: Check if the URL contains ...

Creating a Dynamic System for Converting Numeric Digits to Alphabetical Grades

Utilizing the code provided below, you can calculate a user's grade point average ranging from A+ to E-. Is there a way, within the following fiddle, to not only display the GPA but also convert it into a corresponding letter grade from A+ to E-? Curr ...

What is the best way to position the footer at the bottom of the page without obstructing any content?

I am currently working on a project that utilizes Bootstrap, and I am facing an issue with positioning the footer. Ideally, I want the footer to stay fixed at the bottom of the screen when there is not enough content to fill the page. However, when the con ...

Incorporating EJS Template Body Parameters into AWS Lambda's Handler.js Using Serverless.yml

I have a scenario where I am trying to embed an EJS template named 'ui.ejs' into my handler.js file. The goal is to extract URL query parameters, then pass them to a function called 'ui.js' to retrieve data, which will then be displayed ...

Possibility for using navigator.GetUserMedia in Internet Explorer

How can I access a webcam through JavaScript/jQuery? I have successfully opened the webcam in Chrome and Mozilla, but the navigator.GetUserMedia feature does not work in Internet Explorer. Is there a way to achieve this with JavaScript or jQuery in IE? ...

Having issues initializing jQuery knob on a jQuery mobile webpage

I'm trying to implement the jquery knob plugin to showcase a circular rating system, but I'm encountering difficulties in getting it to display properly. Below is the code snippet I'm using - can someone please point out what's causing ...

When attempting to import my JSX file into page.js, I continue to encounter the error "module not found." How can I troubleshoot and resolve this issue in Visual Studio Code

I recently created a new file called mysec.jsx in the components folder of src. I then used the export function to properly export it. However, when I tried to import this file in page.js using the import function, I encountered an error message that said: ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

Tips for showing an image through a button in Angular 4

Currently, I am in the process of creating a simple website and I have encountered an issue. When I click on a button to display an image, it works fine. However, when I click on another button to display a different image, the previous image remains visib ...

Permanently removing artwork from the Canvas

I am facing an issue with my canvas drawing function. Whenever I clear the drawings on the background image by clicking a button, the old drawings reappear when I try to draw again. How can I permanently delete the cleared drawings so that I can start fr ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Avoiding flickering when the browser back button is clickedAvoiding the flickering effect

As I work on developing an Asp.Net application, a challenge has arisen. In order to prevent users from navigating back to the login page after logging in, I have implemented JavaScript code successfully. However, when clicking the browser's back butto ...

npm's protocol for handling callback errors

While exploring the coding style guidelines by npm, I stumbled upon a rather enigmatic suggestion: Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback. Thi ...