Creating a navbar that sticks to the top of the page

I've been working on some code to create a sticky navbar that remains fixed as I scroll down, but unfortunately, it's not working. I suspect the issue might lie in the CSS, as the HTML and javascript seem fine. Interestingly, this same code has worked successfully on other websites of mine, so I'm puzzled why it's not functioning properly here.

<div id="main-nav">
    <nav>
        <h2 id="logo" class="main-nav">Captain Max from ERA</h2>
        <br>
        <ul class="main-nav">
            <li> <a href="#">Listings</a></li>
            <li> <a href="#">Get in touch</a></li>
            <li> <a href="#">Projects</a></li>
        </ul>
    </nav>
</div>

The script I'm using can be found below. I've reviewed it thoroughly but can't pinpoint any errors at this time.

<script>
var navbar = document.getElementById("main-nav");
var sticky = navbar.offsetTop;
function myFunction() {
    if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky")
    } else {
        navbar.classList.remove("sticky");
    }
</script>

Here is the CSS code associated with the navbar. It appears that a property setting could be affecting the functionality of the sticky feature.

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

.sticky + .content {
  padding-top: 60px;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
    html {
    font-family: 'Raleway', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

nav {
    background-color: #7b8195;
    color: #e9e6df;
    overflow: hidden;
}

#logo {
    font-family: 'Raleway', sans-serif;
    font-size: 250%;
    border-top: 10px;
    padding-right: 150px;
    padding-left: 10px;
    padding-top: 10px;
}

nav li {
    display:inline-block;
    margin-left: 40px;
}

.main-nav {
    float: left;
    list-style: none;
    margin-right: 60px;
    border-bottom: 10px;
    padding-bottom: 10px;
}

.main-nav li a {
    float: right;
    color: #e9e6df;
    text-decoration: none;
    font-size: 90%;
}

.main-nav li a:link,
.main-nav li a:visited{
    padding-bottom: 8px;
    color: #e9e6df;
    text-decoration: none;
    font-size: 90%;
    border-bottom: 2px solid transparent;
    transition: border-bottom 0.2s;
}

.main-nav li a:hover,
.main-nav li a:active{
   border-bottom: 2px solid #e9e6df;
}

You can visit the website by clicking here.

Answer №1

Upon reviewing your website, I noticed that the script tag is not properly closed. It seems like you are missing a closing brace }.

<script>
var navbar = document.getElementById("main-nav");
var sticky = navbar.offsetTop;
function myFunction() {
    if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky")
    } else {
        navbar.classList.remove("sticky");
    }
   }

</script>

https://i.sstatic.net/y34Gq.png

Answer №2

Ensure that everything is accurate, but remember to include the following CSS code snippet for it to function properly:

<style>
#navbar {
  overflow: hidden;
  background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: lightblue;
  color: black;
}

#navbar a.active {
  background-color: blue;
  color: white;
}
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}
</style>

Full script provided below:

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

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
#navbar {
  overflow: hidden;
  background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: lightblue;
  color: black;
}

#navbar a.active {
  background-color: blue;
  color: white;
}
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="navbar">
  <a class="active" href="javascript:void(0)">Home</a>
  <a href="javascript:void(0)">News</a>
  <a href="javascript:void(0)">Contact</a>
</div>

<div class="content">
  <h3>Sticky Navigation Example</h3>
  <p>The navbar will stick to the top when you reach its scroll position.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
</div>
</body>

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

The script tags encountered an issue loading the resource with a status code of 404

Currently working on an ASP.NET MVC project and encountered an issue on one of the pages. Here is the code snippet with a script included at the bottom... @model IEnumerable<PixelBox.Dtos.ItemGetDto> @{ ViewBag.Title = "Index"; } <body> ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

The Powerful Duo: JavaScript and Regex

Having some issues with the code snippet below, I know there's an error in my code but I can't seem to figure out what it is (tried enclosing the code in quotes but that didn't work...) var Regex = require('regex') var regex = new ...

How to Modify the Data in a Dynamic Object within the Vuex Store in a Nuxt Application

Within my Vue/Nuxt project, I have implemented a form where users can add and update dynamic fields for calculating price offers. Upon loading the form, one field is created using the beforeMount lifecycle, with the option for users to add more fields as n ...

Trouble with highlighting the chosen menu item

I have been attempting to implement this code snippet from JSFiddle onto my website. Although I directly copied the HTML, used the CSS inline, and placed the Javascript in an external file, the functionality does not seem to be working properly. Feel free ...

How can I customize the appearance of tab buttons in a QtabWidget using PySide?

Looking for a way to customize the tab buttons on a QtabWidget in PySide. I've managed to style other elements of my custom widget, but can't figure out how to style the QtabWidget tabs. My attempt: self.tabWidget = QtGui.QtabWidget(Form) self. ...

How can I convert an HTML table into a PDF using TCPDF while ensuring that all content is contained within a single div in PHP?

I have successfully converted my JSON API data into an HTML TABLE format and now I am trying to generate a PDF from this HTML TABLE using TCPDF in PHP. Despite trying various methods related to PDF generation using TCPDF, I am facing issues with my code wh ...

What is the best way to search for a specific term in Visual Studio Code/IDE without including another term in the search results?

Is it feasible to search for instances in my code where the term "<img" appears without being accompanied by the term "alt="? This would help me locate all image tags that do not have the alt attribute. Can you provide guidance on how this can be achiev ...

Querying the height of an image element using jQuery and dynamically adding padding if necessary

I've got a Bootstrap carousel displaying images with different heights, and I'm looking to vertically center these images. My approach involves determining the image height, subtracting it from a fixed height value, and if the result is less than ...

Automatic Addition of Row Numbers Enabled

I'm currently exploring coding and experimenting with creating a scorekeeper for family games. I've managed to add rows dynamically and automatically sum up the entered information in the "total" row at the bottom. However, I'm facing an iss ...

What causes the lack of upward movement for a div element when the div above it is floated to the left?

Recently, I've been delving into the world of float property in CSS. This is the HTML code snippet I'm working with: .left { float: left; text-align: center; width: 25%; } .normal { text-align: center; width: 25%; } <div class="lef ...

What is the best way to ensure a div container fills the entire height of the screen?

I am currently working on developing my very first iOS HTML5 app, which is a simple quote application. One challenge I am facing is how to set the height of my container div to match that of an iPhone screen. You can view the design I have so far on this j ...

Implementing ID-based filtering for an array of objects with React

Struggling with filtering an object in an array of objects by its ID using React. Here's the scenario: The app is a Notes app that stores each note with its Title, Text, and created date, utilizing the ID as the key. Currently, I'm working on c ...

Guide to using a Selector in a mixin in VUE

I'm attempting to create a Mixin that will help me calculate the offsetWidth of an element. Here is my Mixin: export const boxWidth = (selector) => ({ mounted() { selector.addEventListener( 'resize', this.setBoxWidth ); ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

Blurring the edges of a div container

I have successfully faded the top of a div, but I am struggling to achieve the same effect for the bottom. I attempted to reverse the CSS properties used for fading the top, but it does not seem to be working as expected. HTML: <div class="container-c ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...