Issue with static navigation bar persistence post-page refresh

My scenario involves a navigation bar embedded in the header that should become fixed at the top of the browser window when the document is scrolled down by a certain amount.

The script I have been using works well, but it causes an issue in Firefox and Chrome (not in Edge and IE11):

When the document is scrolled down and the navigation becomes fixed, if I reload the page using the browser's refresh button or the F5 key, or leave the page and then return, the navigation remains fixed in place.

I attempted to remove the ".fixed" class on every load event, but this approach does not work because there is no actual page reload happening.

It seems like this behavior can only be reproduced in a separate document?!

Does anyone have any suggestions on how I can resolve this problem?

var header, nav, navtop, verticalpos;

function fixed_nav() {

  "use strict";

  verticalpos = window.pageYOffset;

  if (verticalpos >= navtop) {

    nav.setAttribute('class', 'fixed');

  } else {

    nav.removeAttribute('class');

  }

}

function init() {

  "use strict";

  header = document.getElementsByTagName('header')[0];

  nav = header.getElementsByTagName('nav')[0];

  navtop = nav.getBoundingClientRect().top;

}

window.addEventListener('load', init, false);

window.addEventListener('scroll', fixed_nav, false);
* {
  padding: 0px;
  margin: 0px;
}

...
                
<!DOCTYPE html>

...

                    

Answer №1

After running your code through Chrome, I noticed that including a call to the fixed_nav function within your init function will resolve the back button problem you are experiencing.

Answer №2

Resolved my issue by incorporating the pageshow and pagehide events to ensure that the fixed navigation resets even if the document is loaded from cache after using the reset button, forward/backward buttons, or pressing F5.

var html, header, nav, navtop, verticalpos;

function fixed_nav() {

  "use strict";

  verticalpos = window.pageYOffset;

  if (verticalpos >= navtop) {

    nav.setAttribute('class', 'fixed');

  } else {

    nav.removeAttribute('class');

  }

}

function init() {

  "use strict";

  html = document.documentElement;

  header = document.getElementsByTagName('header')[0];

  nav = header.getElementsByTagName('nav')[0];

  navtop = nav.getBoundingClientRect().top;

}

window.addEventListener('load', init, false);

window.addEventListener('pageshow', function() {
  html.scrollTop = 0;
  
  navtop = nav.getBoundingClientRect().top;
  
}, false);

window.addEventListener('pagehide', function() {
  html.scrollTop = 0;
  
  nav.removeAttribute('class');
}, false);

window.addEventListener('scroll', fixed_nav, false);
* {
  padding: 0px;
  margin: 0px;
}

header {
  height: 15rem;
  background-color: lightpink;
}

nav {
  height: 5rem;
  background-color: lightblue;
}

main {
  background-color: lightsalmon;
  display: block;
  /* IE 11 */
}

div {
  max-width: 25rem;
  background-color: rgba(0, 0, 0, 0.2);
  margin: auto auto auto auto;
}

header>div {
  height: 10rem;
}

nav>div {
  height: 100%;
}

main>div {
  padding: 2rem 0rem 2rem 0rem;
}

section {
  padding: 0rem 2rem 0rem 2rem;
}

h2,
p:not(:last-of-type) {
  margin: auto auto 2rem auto;
}

.fixed {
  position: fixed;
  top: 0rem;
  width: 100%;
  transform: translate3d(0, 0, 0);
  /* translateZ-hack */
}
<!DOCTYPE html>

<html>

<head>

  <meta charset="utf-8" />

  <title>Fixed</title>

</head>

<body>

  <header>

    <div></div>

    <nav>

      <div></div>

    </nav>

  </header>

  <main>

    <div>

      <section>

        <h2>Lorem ipsum dolor</h2>

        <p>[Insert sample text here]</p>

        <p>[Insert sample text here]</p>

        <p>[Insert sample text here]</p>

      </section>

    </div>

  </main>

</body>

</html>

Answer №3

1) Ensure that the code is added to your HTML document. 2) Adjust the placement of the navigation element. 3) Implement media queries for responsiveness.

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

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

Automatic Full-Screen Switching Upon Video Playback in HTML5

Currently, I have a video clip set to play when the timer reaches a certain point. My goal is for the video to automatically enter full-screen mode when it starts playing and return to its original position when it stops, as the timer will continue ticking ...

problem encountered while running the npm run watch command

I recently started a project using vue.js and encountered an issue while trying to execute the npm run watch command. The error message received is shown below. https://i.sstatic.net/YOwtQ.png Below is the code from my composer.json file: "scripts": { ...

Help me understand how to display the data in a JSON array

{ "entries": [ { "id": 23931763, "url": "http://www.dailymile.com/entries/23931763", "at": "2013-07-15T21:05:39Z", "message": "I ran 3 miles and walked 2 miles today.", "comments": [], "likes": [], ...

What is the best way to incorporate additional data into an existing Fetch API call within a React component using conditional code?

Alright, here's the deal - I'm dealing with an API that has a whopping 714 rows of data but unfortunately does not provide any image URLs. There’s absolutely no way I’m going to manually input a URL for each and every row or object in the dat ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

The $scope within the $ionicplatform is not functioning as expected

I've been working on an application, but it doesn't seem to be functioning correctly. Typically, when we add a value to the scope, I expect it to update in the application. Here is the snippet from index.html: <body ng-app="starter"> <i ...

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

I am having trouble getting JQuery tablesorter to work, what am I missing?

As a newcomer to jQuery, I am attempting to implement Tablesorter, but unfortunately, it does not seem to be functioning properly on my table (the styling remains unaffected by the tablesorter css, and the sorting functionality is non-existent). Below is ...

Content not being displayed by Javascript

I'm having trouble displaying content using JavaScript DOM. Every time I try to run my code, the page comes up blank. Here is an example of my HTML file: <!DOCTYPE html> <html> <head> <title>Radiant HQ</titl ...

The issue persists as the ng-change directive fails to function despite the presence of ng-model in AngularJS

Greetings everyone. Despite searching online for a solution to my issue, I have been unable to resolve it. Below is the HTML5 code snippet I am working with: <!DOCTYPE html> <html> <head> </head> <body ng-app="myApp ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Resize a div within another div using overflow scroll and centering techniques

Currently, I am working on implementing a small feature but am facing difficulties with the scroll functionality. My goal is to zoom in on a specific div by scaling it using CSS: transform: scale(X,Y) The issue I am encountering lies in determining the c ...

Troubleshooting Issue: Unable to Display Dropdown Menu with Bootstrap 5 and ReactJS

Attempting to showcase a simple NavBar from the bootstrap documentation (https://getbootstrap.com/docs/5.0/components/navbar/) in React. I installed Bootstrap using npm I bootstrap. Here is the structure of my App: https://i.sstatic.net/h41mr.png Below ...

Unique keyboard occasion

Currently, I am utilizing Vue with the Quill editor placed within a div and using the deprecated DOMSubtreeModified. My goal is to trigger an event that will send an API request to save the editor's content to the database. The code snippet below hig ...

What is the best way to eliminate the underline from a hyperlink?

I need help removing the underline from links on a website. I attempted to use "text-decoration: none;" but it didn't work. Could someone point out what syntax mistake I made? Or perhaps suggest a better way to eliminate the underline? <head> ...

Difficulty arises when switching between the coordinates of a wavefront (.obj) in three.js

Currently, I am dealing with a slider in my HTML code that has values ranging from 1 to 2. When the slider value is set to 1, I intend to adjust the coordinates of my wavefront as described by arrayMin. Conversely, when the slider is at 2, I wish for the w ...

Converting a local timezone date object to a UTC timezone date object in JavaScript: a simple and streamlined approach

Looking to convert a Date object with local timestamp to a Date "object" with UTC timestamp. I came across a method that does the job, indeed: var d = new Date(); // creates Date object with local timezone var s_str_utc = d.toUTCString(); ...

Tips for ensuring that the logic within a custom vue directive is only executed when the corresponding element is clicked

I am currently facing an issue where the directive I attach to an element is being executed when the page loads, but I want it to run only when that element is clicked. How can I achieve this functionality? directives: { 'new-dir': ...

With a simple click of a button, I aim to have the ability to set a variable to true

I am looking to create a button that changes to true in the Script section. This will allow for a random number to be displayed in the paragraph element. <!doctype html> <html> <button id="button"> random number </button> ...