JavaScript Enhanced Sticky Navbar

Hey there! I've been working on creating a sticky navbar using vanilla JavaScript. My goal is to make the logo and navbar stay sticky when scrolling, but unfortunately, I'm running into some errors that I can't seem to fix. I would really appreciate it if someone could take a look at the code below and help me out. Thank you!

let nav = document.querySelector('.nabar');
let topToNav = nav.offsetTop;
let logo = document.querySelector('.logo');

function stickyNav () {
    if(window.scrollY >= topToNav) {
        logo.style.paddingTop = nav.offsetHeight + 'px';
        logo.classList.add('fixed');
    } else {
        logo.style.paddingTop = 0;
        logo.classList.remove('fixed');
    }
}
window.addEventListener('scroll', stickyNav);
.nabar{
  background-color: darkslategrey;
  padding: 15px 0px;
}
.nabar li{
  list-style: none;
  display: inline;
  font-size: 20px;
  padding: 0px 15px 0px 15px;
}
.nabar ul {
  text-align: center;
}
.nabar a:hover {
  text-decoration:none;
  color: white;
}
.nabar a{
  color: white;
}
.fixed .nabar {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  box-shadow: 0 3px 6px rgba(black, .3);
}
.test{
  height: 600px;
  background: yellow;
  }
.test2{
  height: 609px;
  background: green;
  }
.logo{
  height: 100px;
}
.logoimg{
  width: 240px;
  height: 100px;
  margin: 0 auto;
  display: block;
}
<div class="logo">
      <img class="logoimg" src="http://pngimg.com/uploads/car_logo/car_logo_PNG1648.png">
    </div>
    <div class="nabar">
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">Features</a></li>
          <li><a href="#">Portfolio</a></li>
          <li><a href="#">Services</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Contact Us</a></li>
        </ul>
      </div>
      <div class="test">
        </div>
          <div class="test2">
        </div>

Answer №1

Make sure to group your navigation and logo elements together to make them stick at the top of the page, like the example code provided below.

To maintain the width of your navigation bar, use position:sticky; instead of position:fixed;

window.onscroll = function() {stickyNav()};
var mynavbar = document.getElementById("my-navbar");
var sticky = mynavbar.offsetTop;
function stickyNav() {
  if (window.pageYOffset > sticky) {
    mynavbar.classList.add("fixed");
  } else {
    mynavbar.classList.remove("fixed");
  }
} 
.nabar{
  background-color: darkslategrey;
  padding: 15px 0px;
}
.nabar li{
  list-style: none;
  display: inline;
  font-size: 20px;
  padding: 0px 15px 0px 15px;
}
.nabar ul {
  text-align: center;
}
.nabar a:hover {
  text-decoration:none;
  color: white;
}
.nabar a{
  color: white;
}
.fixed {
  position: sticky;
  width: 100%;
  top: 0;
  left: 0;
  box-shadow: 0 3px 6px rgba(black, .3);
}
.test{
  height: 800px;
  background: yellow;
  }
.logo{
  height: 100px;
}
.logoimg{
  width: 240px;
  height: 100px;
  margin: 0 auto;
  display: block;
<div class="logo">
        <img class="logoimg" src="http://pngimg.com/uploads/car_logo/car_logo_PNG1648.png">
  </div>

  <div id="my-navbar" class="nabar">
          <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Features</a></li>
            <li><a href="#">Portfolio</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact Us</a></li>
          </ul>
  </div>
<div class="test"></div>

view an example on codepen

Answer №2

When you see the css .fixed .primary-nav with a space in between, it is referencing this specific element:

<div class="fixed">
    <div class="primary-nav" />
</div>

Therefore, the following css code will not have any effect in your current setup.

.fixed .primary-nav {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  box-shadow: 0 3px 6px rgba(black, .3);
}

If you remove the .primary-nav part, keep in mind that you do not have an element with that class...

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 Angular select asynchronously within a custom directive

Despite my efforts, I am struggling to get an angular select with async to work properly. It seems to be mostly working, but not entirely. Consider the controller below: $scope.stuff = {}; $scope.stuff.blah = "SOME_KEY"; External.list().then( function ...

Tips for transforming a React sign in component into an already existing Material UI sign in component

I am looking to revamp my current sign-in page by transitioning it into a material UI style login page. Displayed below is the code for my existing sign-in component named "Navbar.js". This file handles state management and includes an axios call to an SQ ...

The values are not being displayed in the local storage checkbox

I attempted to transfer checkbox values to another HTML page using local storage, however they were not appearing on the other page Here is my page1 HTML code snippet: <input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW"> ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

Get the docx file generated with Flask and VueJS

I've been grappling with the challenge of downloading a docx file in VueJS. Initially, I attempted to generate the file on the frontend, but it kept getting corrupted. To solve this issue, I resorted to using Flask to create the docx file, which worke ...

Ensure the browser back button navigates to the login page seamlessly, without displaying any error

A scenario I am working on involves a Login jsp that accepts a user email and sends it to a servlet. If the provided email is not found in the database, the servlet redirects back to Login.jsp with an attribute "error". Within the header of Login.jsp, ther ...

Getting hold of HTML elements in a div on a different page

Recently diving into the world of html/javascript, I find myself engaged in a project where I'm loading an external html page within a div. The loaded content looks like this: <div class="content" id="content"> <object ty ...

Issue with displaying jQuery class names accurately

I am implementing jquery.scrollablecombo.js for a dropdown menu using jQuery. However, when I include it in my HTML code, the class attribute is displayed as "classname" instead of "class." See the example below: <div classname="searchBar cb_selectMain ...

Angular.js fails to update the repeater when $scope.var is modified, only refreshing after a manual refresh

I always thought two-way binding was just an Angular thing: When I submit a form to the controller, my input is displayed on the page. However, I have to refresh the page to see the new input: $scope.loadInput = function () { $scope.me.getList(&apos ...

How can I retrieve the value of a sibling's child using jQuery/Ajax?

I'm currently troubleshooting an AJAX comment feature that should activate when a user clicks "open comments." My PHP script is successfully returning data and the ajax call status is "200 OK," so it seems to be functional. However, I am struggling t ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...

Utilize querySelectorAll to inspect class properties

When exporting a table to CSV, I have implemented the following logic: var cols = rows[i].querySelectorAll("td, th"); While this method works well, users are able to hide/display columns as they desire. Since AngularJS is used, the hidden columns are mar ...

Having trouble navigating with router.navigate and utilizing local storage?

I have a code that utilizes router.navigate to direct the user to a specific location abrirLista(categoria, id) { localStorage.setItem('categName', JSON.stringify(categoria)); const slug = slugify(categoria); this.router.navigate(['/lista&ap ...

Using AngularJS, you can easily preselect an option in a select menu that is populated using ng-options

Exploring how to use AngularJS ng-option directive to populate a select menu and set a default option. The JSON data retrieved by AngularJS: {"AF":"Afghanistan","AX":"\u00c5land Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD"} The ...

Is there a way to prevent a button from being clicked until a certain callback function is triggered

I am struggling with configuring my contact form to disable a button when the form is not valid or a recaptcha is not selected. <form name="contactForm" data-ng-controller="ContactCtrl" novalidate> ... <input class="form-control" name="email" typ ...

What are the steps for sorting objects in an array by their data type attribute?

I am currently working with a JavaScript array of people objects that is dynamically rendered from JS. My goal is to implement a filter on the objects based on the selection made in the dropdown menu and matching it with the department attribute specified ...

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...

What is the most effective method for transforming a space-separated list of classes into a jQuery selector?

Is there a quick and efficient method for converting a space-separated list of classes like: classOne classTwo classThree into a selector such as: $('.classOne .classTwo .classThree') I am considering utilizing either a loop to construct a se ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

What is the best method for interacting with multiple links in Puppeteer?

As a beginner with puppeteer, I am diving into the world of web scraping by attempting to create a simple scraping task. My Plan of Action The plan is straightforward: Visit a page, Extract all <li> links under a <ul> tag, Click on each < ...