html navigation bar is not functioning as intended in my webpage

I'm facing an issue with my navbar menu. I implemented some JavaScript code to make the navbar sticky while the user scrolls, but it's not working as expected. The navbar is not staying sticky when the page is scrolled.

Could someone please review my code and help me figure out what might be the problem?

Here is the JavaScript code snippet I used:

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

// Get the navbar
var navbar = document.getElementById("thor");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function seeFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
<div id="thor" class="ttm-header-wrap">
  <!-- ttm-stickable-header-w -->
  <div id="ttm-stickable-header-w" class="ttm-stickable-header-w clearfix">
    <div id="site-header-menu" class="site-header-menu">
      <div class="site-header-menu-inner ttm-stickable-header">
        <div class="container">
          <!-- site-branding -->
          <div class="site-branding">
            <a class="home-link" href="index.html" title="Planwey" rel="home">
              <img id="logo-img" class="img-center" src="TEIA png big.png" alt="logo-img">
            </a>
          </div>
          <!-- site-branding end -->

          <div id="site-navigation" class="site-navigation">
            <div class="ttm-menu-toggle">
              <input type="checkbox" id="menu-toggle-form" />
              <label for="menu-toggle-form" class="ttm-menu-toggle-block">
<span class="toggle-block toggle-blocks-1"></span>
 <span class="toggle-block toggle-blocks-2"></span>
 <span class="toggle-block toggle-blocks-3"></span>
 </label>
            </div>
            <nav id="menu" class="menu">
              <ul id="modify" class="dropdown">
                <li class="active"><a href="index.html">Home</a>

                </li>
                <li><a href="#">About</a>
                  <ul>
                    li><a href="about-us.html">TEIA</a></li>
                <li><a href="services-1.html">Board Members</a></li>
                <li><a href="services-2.html">Agenda</a></li>
                <li><a href="our-event.html">Vision & Mission</a></li>

                </ul>
                </li>
                <li><a href="#">Members</a>
                  <ul>

                    <li><a href="portfolio-overlay.html">Membership Type</a></li>
                    <li><a href="portfolio-classic.html">Code of Conduct</a></li>
                    <li><a href="portfolio-overlay.html">Membership Benefits</a></li>
                    <li><a href="portfolio-classic.html">Register/Join</a></li>
                  </ul>
                </li>
                <li><a href="#">Resources</a>
                  <ul>
                    <li><a href="blog.html">Upcoming Events</a></li>
                    <li><a href="blog-grid.html">Previous Events</a></li>
                    <li><a href="single-blog.html">Press Release</a></li>
                    <li><a href="single-blog.html">Gallery</a></li>
                  </ul>
                </li>
                <li><a href="contact-us.html">Contact Us</a></li>
                <li class="nyan" style="background-color: #00bfff; color: white !important; "><a href="#">Log In</a>
                  <ul>
                    <li class="sss"><a href="admin">Admin</a></li>
                    <li><a href="members">Member</a></li>

                  </ul>
                </li>
              </ul>
            </nav>
          </div>
          <!-- site-navigation end-->
        </div>
      </div>
    </div>
  </div>
</div>

I previously had another piece of JavaScript code that made the navbar shrink on scroll, but I removed it since I didn't want that functionality. The old code snippet looked like this:

$(window).scroll(function(){
    if ( matchMedia( 'only screen and (min-width: 1200px)' ).matches ) 
    {
        if ($(window).scrollTop() >= 30 ) {
            $('.ttm-stickable-header').addClass('fixed-header');
            $('.ttm-stickable-header').addClass('visible-title');
        }
        else {
            $('.ttm-stickable-header').removeClass('fixed-header');
            $('ttm-stickable-header').removeClass('visible-title');
        }
    }
});

Answer №1

Try utilizing CSS instead of JavaScript with position: sticky

#thor {
    position: sticky;
    top: 0;
}

reference: MDN

Answer №2

try using this CSS code snippet

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

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

var head = document.getElementById("thor");
var stickies = head.offsetTop;

function stickEffect() {
if (window.pageYOffset > stickies) {
head.classList.add("stickiness");
} else {
head.classList.remove("stickiness");
}
} 
.top-container {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
}

.content {
  padding: 16px;
}

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

.sticky + .content {
  padding-top: 102px;
}
<div class="top-container">
  <h1>Scroll Down</h1>
  <p>Scroll down to see the sticky effect.</p>
</div>

<div class="header" id="thor">
  <h2>My Header</h2>
</div>

<div class="content">
  <h3>On Scroll Sticky Header</h3>
  <p>The header will stick to the top when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</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>

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

Can object methods be called using inline event attributes in an HTML tag?

Exploring the depths of core JavaScript has been my latest obsession. It's fascinating how we can easily trigger functions within the global context using events like this. HTML <span class="name" onclick="clicked()">Name</span> JavaSc ...

Unable to retrieve field data in controller from view after submitting form through AJAX

I have been working with CodeIgniter, and I am facing an issue where I cannot retrieve field data from the view to the Controller when submitting a form using AJAX. Despite spending the past two days trying to solve this problem, I have been unsuccessful. ...

Issue with AWS SDK client-S3 upload: Chrome freezes after reaching 8 GB upload limit

Whenever I try to upload a 17 GB file from my browser, Chrome crashes after reaching 8 GB due to memory exhaustion. import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage& ...

Adjust the background color dynamically as you scroll, given that I am using a linear-gradient

Is it possible to change the color background using JavaScript while scrolling, especially if I have a linear gradient like this: background: linear-gradient(115deg, #42c344 0%,#42c344 40%,#c4efc4 40%,#ffffff 40%,#ffffff 100%); background-attachment: fi ...

To combine both jquery-1.min.js and jquery.min.js is essential for achieving optimal functionality

When using these two files, only one of them can work on a page. <script src="jquery.min.js"></script> <script src="jquery-1.min.js"></script>//Only the second one works Alternatively, if the order is changed: <script src="jq ...

Encountering an Express.js HTTP 500 ERROR when using res.send("Some text"); is working on the page, however, the error occurs when trying to use res.render('file');

My website has a page located at /request that features a form. The form's method is POST and the action leads to /request. In the POST handler in request.js, the intention is to take action with the form data, like storing it in a database, and then ...

Adding several <div> elements with the correct indices

I need help with a dynamic form that requires users to select a state before revealing the corresponding cities within that state. <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="s ...

Responsive Design of Iframe Not Adjusting Properly

My website features an embedded Google map in an iframe: <iframe src="https://www.google.com/maps/d/u/0/embed?mid=EXAMPLE" style="top:0px; position:fixed; float:left; width:35%; height:400px;"></iframe> Adjacent to the map, ...

How can I update data in Select2 after it has been initialized?

After initializing select2, I am trying to set an array of data in the following way: var selection = $('#selection').select2({}); selection.data([ {id: 1, text: 'value1'}, {id: 1, text: 'value1'} ]); However, I am encou ...

The InfoWindow on Google Maps is positioned above the Marker

My struggle lies in positioning the infowindow above my Google Maps API marker, as the infowindow keeps hiding the marker. I attempted using CSS to adjust the position of both elements, but unfortunately, it didn't have the desired effect. Here is th ...

"Implement a smooth transition effect lasting 1000 milliseconds when a class is added via

I'm attempting to use the fadeIn 1000 effect when a class is added through a Click function. I have already attempted this: http://jsfiddle.net/rf7mudL5/ HTML <span class="date-outer">Text will Red on fadeIn</span> <button class="mo ...

AngularJS: Issue with directive function not being executed

I created a directive in my code, but for some reason the function I provided to define the directive is not being called. It was working perfectly fine before, and now it just suddenly stopped without any clear explanation. Below is the code snippet of m ...

Press the button in an HTML document to activate JavaScript

What could be the issue with my code? I have a button in HTML <a class="btn btn-warning btn-mini publish-btn" href="#" data-rowid="@computer.id" data-toggle="modal" data-target="#myModal">Outdated</a> and my modal <fieldset style="text-al ...

Preserving reference equality while passing props in React

Consider a scenario where a function dynamically generates some props for a component, and you want to pass all of them without specifying each individual prop that the function might generate. Typically, this can be achieved using the spread operator. How ...

Chrome browser experiencing a disappearing vertical scroll bar issue on a Bootstrap Tab

<div class="tabs-wrap left relative nomargin" id="tabs"> <ul class="nav ultab" id="fram"> <li class="active"><a href="#history" data-toggle="tab" id="history1" >History< ...

Is the column-fill property malfunctioning in Chrome?

column-fill: balance; is said to "equally divide content between columns". It appears to be functioning correctly in Firefox and Edge. However, Chrome (and Opera) seem to have a strong aversion to the second column, leaving it mostly empty. It seems to be ...

Running multiple controller functions in nodejs can be achieved by chaining them together in the desired

Currently, I am working on the boilerplate code of mean.io and adding a password reset email feature to it. Whenever a user requests a password reset with their email as a parameter, I generate a unique salt (resetid) and send them an email with a link con ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

Creating overlapping layouts with absolute positioning in Bootstrap leads to a visually appealing

I'm currently working on a layout that involves absolute positioning elements, similar to the one shown in this example: https://i.sstatic.net/TixbZ.jpg It seems like the elements are overlapping and not clearing properly. I've been looking for ...

The successful execution of $.ajax does not occur

Starting out with ajax, I wanted to create a simple add operation. Here is the code that I came up with: HTML: <!doctype html> <html> <head> <title>Add two numbers</title> <meta content="text/html;charset=utf-8" h ...