The sticky navigation bar isn't functioning properly, even though the code worked perfectly on W3School

I recently encountered an issue while trying to create a sticky navbar that would remain fixed after scrolling past a certain point. I found and customized some code from w3schools that included an animation effect, and it worked perfectly in their demo. However, when I implemented the same code into my own project, it failed to function properly. What could be the reason behind this discrepancy, and how can I rectify it?

For reference, I have shared the relevant code snippet in this fiddle: https://jsfiddle.net/yL3e9Lk4/

I have also created a fiddle for the working demo on W3schools, which you can access here: https://jsfiddle.net/o65zca6w/

Below is the HTML snippet:

// JavaScript code
var navbar = document.getElementById("navbar");
var sticky = stickpoint.offsetTop;

function StickyNav() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
    navbar.classList.add("slide-in-top")
    navbar.classList.remove("nav")
  } else {
    navbar.classList.add("nav")
    navbar.classList.remove("sticky");
    navbar.classList.remove("slide-in-top")
  }
}
// CSS code
body {
  overflow-x: hidden;
  margin: 0px;
  background: #333;
}

.nav {
  list-style-type: none;
  overflow: hidden;
  display: inline-block;
  z-index: 2;
  position: absolute;
  border: solid;
  border-color: red;
}

/* Remaining CSS code omitted for brevity */
<!-- HTML code -->
</div></div>

Answer №1

Does this meet your requirements?

body {
  /*background-color: #333;*/
  overflow-x: hidden;
  margin: 0px;
  background: #333;
}

.nav {
  list-style-type: none;
  overflow: hidden;
  display: inline-block;
  z-index: 2;
  position: absolute;
  border: solid;
  border-color: red;
}

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

.li {
  text-align: center;
}

.flex-container {
  display: flex;
  display: -webkit-flex;
  -webkit-align-items: center;
  align-items: center;
}

.flex-item {
  margin: 5px;
}

.resize-anchor {
  display: inline-block;
  height: auto;
  width: 300px;
}

.hplogo-a {
  display: inline-block;
  height: auto;
  width: 200px;
  min-width: 200px;
}

a {
  display: inline-block;
  color: white;
  text-decoration: none;
  white-space: nowrap;
}

a:hover {
  color: #D1946F;
  text-decoration: none;
}

a:link {
  color: #D1946F;
  text-decoration: none;
}

.nav-link {
  margin: 0px 10px 30px 10px;
  font-family: Calibri;
  font-size: 18px;
  font-style: normal;
  font-variant: normal;
  line-height: 26.4px;
  padding: 0px 10px 0px 10px;
  margin-top: 20px;
}

img {
  width: 100%;
}

p {
  color: white;
  text-align: center;
}

h5,
h3 {
  text-align: center;
  color: #D1946F;
}
<body onscroll="myFunction()">
  <div id="navbar" class="li flex-container nav">
    <a class="nav-link flex-item col-md-2" href="#">PHOTOGRAPHER</a>
    <a class="nav-link flex-item col-md-2 " href="#">PORTFOLIO</a>
    <a class="hplogo-a flex-item col-md-2" href=""><img id="logo" src="http://www.kraftheinzcompany.com/pressroom/images/view/kraftlogolarge.jpg" alt=""></a>
    <a class="nav-link flex-item col-md-2" href="#">INVESTMENT + FAQ</a>
    <a class="nav-link flex-item col-md-2" href="#">BLOG</a>
  </div>



  <div class="container bottom PHOTOGRAPHER">


    <h3>THROUGH MY LENS... YOUR STORY.</h3>
    <p>Shawty had them Apple Bottom Jeans [Jeans] Boots with the fur [With the fur] The whole club was lookin at her She hit the floor [She hit the floor] Next thing you know Shawty got low low low low low low low low Them baggy sweat pants and the Reeboks
      with the straps [With the straps] She turned around and gave that big booty a smack [Ayy] She hit the floor [She hit the floor] Next thing you know Shawty got low low low low low low low low Read more: T-Pain - Apple Bottom Jeans Lyrics | MetroLyrics
    </p>;

    <h5>THE COLLECTION PORTFOLIO</h5>

    <button></button>
    <button></button>
    <button></button>
    <button></button>
    <button></button>

    <p>© Copyright 2049 Orange People Photography. All Rights UnReserved.
    </p>
    <img src="https://upload.wikimedia.org/wikipedia/commons/e/e0/Long_March_2D_launching_VRSS-1.jpg" alt="">
    <p id="stickpoint">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut commodi rerum labore, dicta dolorem tempore. Labore animi obcaecati fugit, nesciunt doloremque dignissimos rerum consectetur asperiores, laboriosam iste architecto tempore vel inventore necessitatibus
      pariatur perspiciatis dolore iusto accusamus facere ipsam.;
    <br>;
  </div>;
  <script>;
    var navbar = document.getElementById("nabvar");
    var sticky = stickpoint.offsetTop;;

    function myFunction() {
      if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky");
        navbar.classList.add("slide-in-top");
        navbar.classList.remove("nav");
      } else {
        navbar.classList.add("nav");
        navbar.classList.remove("sticky");
        navbar.classList.remove("slide-in-top");
      }
    };
  </script>;
</body>
;
;

I am still in training. This is my interpretation.

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

Exploring the Depths with a Javascript Canvas Deep Zoom Library

I am faced with the task of creating a detailed zoom mosaic using an HTML5 Canvas Element, consisting of thousands of roughly 512x512 images. However, I am striving to minimize reinventing the wheel in the process. Instead of merging numerous large images ...

How to retrieve the value of an observable from a regular JavaScript array in Knockout JS?

Context In my project, I am working with a plain JavaScript array that starts off empty but gets populated with Knockout observables later on. These values are numbers and I need to compare them with values in another Knockout observable array. The issue ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...

A guide on updating object values within an array using map in React

Is there a method to calculate the total sum of specific values from an array of objects? Example array: const exampleArray = [ {item_id: 1, quantity: "3"}, {item_id: 2, quantity: "5"}, {item_id: 3, quantity: "2"} ] In this case, I want to add up the qua ...

Expo is having trouble locating the module "color-convert" - such a frustrating problem

Having an issue! I ran the command npm start in my terminal and received the following error: Starting project at /home/pc/Documents/Projects/Mobile/weather_app Developer tools running on http://localhost:19002 Cannot find module 'color-convert' ...

Image loading failure detected in ReactJS

In my current project using Reactjs (Nextjs framework), I encountered an issue where I am unable to display an image on a page without specifying the "height" and "width" attributes in the Image tag. I attempted the following code snippet but the image is ...

Alteration in relational shift of division placement

My webpage is divided into three sections with the following proportions: 15% - 65% - 20% In the right section, there is a div with the ID alchemy. I want to set the height of this div using <div style="height:150px;">. However, when I set the heig ...

How can I trigger a PHP function from within an HTML onClick() event?

While I have come across a response on stackoverflow regarding form submission, my query pertains to a different implementation. I am in need of calling a function that registers a variable in $_SESSION[], and then redirects to another page (html/php). I ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

Incorrect Results from Angular Code Coverage

Currently using Angular.js, Karma, Karma-coverage (Istanbul), and Jasmine for my stack. While conducting Code Coverage analysis on my app, I encountered an issue which leads to my question - Service A is showing up as covered by tests (in green) even thou ...

The XMLHttpRequest onload() function is failing to pass an instance of the XMLHttpRequest object

I am facing an issue with a function that sends a basic AJAX request to my server. The JavaScript code in the browser is as follows: function testRequest() { var xhr = new XMLHttpRequest(); xhr.onload = () => { console.log("RESPONSE R ...

Utilizing the Authorization Header in WebSocket within a React Electron Application

Struggling to establish a connection with a secure websocket that requires Bearer Auth via Header. Despite popular advice, it seems setting headers for WebSockets is not straightforward. How can I achieve this in a React Electron App? Currently using the & ...

Show a success message once the jQuery Ajax operation is successful and then refresh the page

I am looking to implement a feature where a Bootstrap alert message is shown immediately following a successful AJAX request and page refresh. success: function(res) { window.location.reload(); $('#success').html('<div class=&qu ...

Scroll to the top of jQuery DataTables when clicking pages in a random order from the bottom to the top and

In my current project, I am working with jQuery Datatables and I need to customize its default behavior. Currently, when I navigate to page 61, the page scroll remains at the bottom of the page. However, if I then click on a lower page number like 60, th ...

An issue has been identified in the bubble sort algorithm causing certain numerical lists to not be properly sorted when implemented in NodeJS

I am just beginning to learn about algorithms and have started with the bubble sort. I wrote my own implementation and it seems to work well most of the time when sorting a list of numbers from 1 to 100. However, occasionally there is one random number th ...

Attempting to conditionally map an array of objects

I am currently working on conditionally rendering content on a screen. My main task involves manipulating an array of 3 objects with sub-objects, stored as the initial state in my reducer (using dummy data). The layout includes a customized SideNav bar wit ...

How to submit the next row using jQuery AJAX only when the previous submission is successful without using a loop - could a counter

Currently, I am dealing with loops and arrays. My goal is to submit only the table rows that are checked, wait for the success of an Ajax call before submitting the next row. Despite trying various methods, I have not been successful in achieving this yet. ...

Argument not accepted in JavaScript

Currently, I am encountering a unique error message while working with a complex function that iterates through elements in my JavaScript onSuccess event. The error I am seeing is: exception encountered : {"message": "Invalid argument.", "description": " ...

Retrieve: proper authentication credentials were not provided

Whenever I make a request, everything works fine and I receive the data: const get_players = async()=>{ const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/') const data = await response.json() console. ...

Tips on retaining the value of $index in ng-repeat and storing it within the array

I currently have a cart for shopping. The code for the "add to cart" function looks something like this (shortened): "add" : function(code) { codes.push({ "id" : code.id, "order" : "N/A", ...