Set navigation to switch to `position: fixed` after scrolling a certain distance

I'm currently working on adjusting the navigation to have a position: fixed right below the black header. I suspect that there might be some necessary tweaks needed in the JavaScript code, but I'm unsure about the specific changes required at this stage.

Here's the fiddle link for reference: http://jsfiddle.net/kgnkxemd/2/

HTML Structure

<div>
    <header></header>
    <div></div>
    <div></div>
    <ul id="site-navigation">
        <li>nav 1</li>
        <li>nav 2</li>
        <li>nav 3</li>
        <li>nav 4</li>
    </ul>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

CSS Styling

div {
    height: 100px
}
header {
    background: #000;
    height: 60px;    
    position: fixed;
    top: 0;
    width: 100%;
}
#site-navigation {
    background: yellow;
}
#site-navigation li {
    display: inline-block;
}
#site-navigation.fix-nav {
    position: fixed;
    top: 60px;
    width: 100%;
}

JavaScript Logic

// Fixed Navigation Implementation
var nav = $("#site-navigation");

nav.on("scroll", function(e) {

  if (this.scrollTop > 60) {
    nav.addClass("fix-nav");
  } else {
    nav.removeClass("fix-nav");
  }

});

Answer №1

Almost there, but a few tweaks are needed.

Instead of attaching the scroll event to the nav element, target the window since that's what actually scrolls. Make sure to use $(window).scrollTop() (or $(this).scrollTop() within the scroll event) to get the window's current scroll position.

$(window).on("scroll", function(e) {
  if ($(this).scrollTop() > 60) {
    nav.addClass("fix-nav");
  } else {
    nav.removeClass("fix-nav");
  }
});

By implementing these adjustments, you'll achieve the desired effect. Check out the updated code here: http://jsfiddle.net/kgnkxemd/3/

Answer №2

scrollTop() is not a property but a function that needs to be updated in your script as shown below.

jQuery(document).ready(function($){
  var nav = $("#site-navigation");
  $(document).on("scroll", function(e) {
    if ($(document).scrollTop() > 60) {
      nav.addClass("fix-nav");
    } else {
      nav.removeClass("fix-nav");
    }     
  });    
});

Check out the DEMO here

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

Why doesn't the browser redirect even though Fiddler is indicating otherwise?

The 'Execute' function is triggered by XmlHttpRequest. $.ajax( { async: false, url: 'Task/Execute/1' }); The 'Execute' function initiates a redirect ...

Creating a unique Voronoi Diagram wrap

I am currently working on the creation of a fantasy-style map that is procedurally generated using the cells of a Voronoi diagram to determine different terrains. While working on the tectonic plate generation, I came to the realization that having wrappi ...

Options for jquery UI autocomplete only appear after the second search

Here is the code snippet I am working with: $("#hifind-find").keyup(function(){ var val = $(this).val(); if (val.length > 1) { var posturl = '/hifind/jquery_ui/autocomplete/'+val; $.post(posturl, function(r) { $("#hifin ...

"Node.js is throwing a 'postgres: relation does not exist' error even though the table it's referring to

After executing a psql command to create table users, I encountered some issues. CREATE TABLE users ( id integer NOT NULL, username text ); Although I can retrieve rows with SELECT * FROM users; When using node.js and the pg module for making c ...

Tips for personalizing Bootstrap columns using identical class names?

Is there a way to customize the background color of each individual .col-5 within the same row while using Bootstrap and a custom CSS file? Changing the styles for one column seems to affect all columns with the same class name. Edit: I'm looking f ...

What could be causing my image to lose responsiveness as the screen size gets smaller?

Struggling to figure out why the image is not responsive when the screen size decreases. I'm trying to create a signature block where the image adjusts in size, preventing the wrapper from stacking into two columns and keeping it as one. I've tr ...

Measuring the Unquantifiable: Embracing Undefined Values in MongoDB

Issue Despite multiple attempts, the Node.js MongoDB library consistently returns undefined for collection.count({}). I have thoroughly researched previous solutions to similar questions without success - the problem persists and the result is always unde ...

An unassigned variable automatically sets the disabled attribute to true on an input field

Is this behavior a problem or normal? Consider the following form structure: <form #form="ngForm" > <div> <label>field1</label> <input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar" /> ...

Transforming a fluid webpage into a fixed page

Currently, I am undertaking a project that involves converting a dynamic website like Adobe Spark into a static HTML+CSS page, which will eventually be transformed into a PDF. The interactivity of the website relies heavily on Javascript modifying CSS+HTML ...

Some places may not have detailed information available when using the Google Places API

Greetings I am currently in the process of developing a page on my website that utilizes the Google Places API along with the user's geographical coordinates (latitude, longitude) to locate nearby restaurants. In my code, I have implemented a functio ...

Unable to retrieve array element using named key in JavaScript

I am having trouble passing an array of objects to a php page within a larger data structure. My JavaScript code is attempting to replicate this structure and pass it via json. In the php script, the array keys have been set as names that I will need late ...

Tips on keeping a Material UI menu item open when clicked

My menu consists of a single item, which is a text field along with a button. The idea is to input some information, save it by clicking the button, and then close the menu either by hitting "close" or the original button again. How can I stop the MenuItem ...

Display a specific element only if another element exceeds a specified height

A snippet of HTML code is given below: <span class="day-number">{{day-number}}</span> <div class="event-box"> <div class="event-container"> </div> <div class="more-events">more ...</div> </div> The .e ...

Once a WordPress user includes a php file

For the past three days, I've been grappling with this issue... calling on all experts for assistance! I manage four distinct Wordpress membership sites, each with its own branding. My goal is simple - to have a .wav file play the plan's name wh ...

How to Share Your Vuejs Component with the World by Publishing it on npm

I have recently developed a Vue.js 2 project using webpack which consists of 2 components. My goal is to share this project as an npm package so that the components can be easily reused in multiple projects. After publishing the project on npm with npm pu ...

blurring out of an input field and a division element

I am currently working on creating a dropdown suggestion box that hides when the input field and dropdown box are no longer in focus. My HTML code: <input type="text" id="user_address"> <div id="user_address_sg">SUGGESTION</div> <di ...

What is the best way to retrieve duplicate input values using JavaScript?

Hey there! I have created a button that, when clicked, will add two input fields one after the other. I achieved this using the clone() function. However, my issue arises when I input values into each field and then click the submit button, as I only recei ...

How does margin:auto differ from using justify-content and align-items center together?

If you want to center both horizontally and vertically at the same time, there are two easy methods available: Option One .outer { display:flex; } .inner { margin:auto; } Option Two .outer { display: flex; justify-content: center; align-items ...

Is there a way to create a bar chart that begins at the 0 point of the y-axis instead of starting from the base of the SVG?

Is there a way to start the bar chart from the 0 point of the y-axis instead of the very bottom of the svg? How can I achieve this? let url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json"; const padding = 5 ...

Utilizing sub-object attributes as ng-model in AngularJS

I'm working with a dropdown that is connected to a user object structured like this: { userId:1, userLogin:"test", locale: { localeCode:"en-US" } } This structure originates from a C# model class where User and Locale are associated classes (U ...