The sticky navigation bar hack (implementing fixed positioning with jQuery)

Essentially, when the navigation bar (or any other element) reaches the top of the page or window, a class called "sticky" is added to the element and CSS styles it as fixed. This functionality acts like an IF statement - if the element is far from the top, the class is removed and the element returns to its normal state.

I have thoroughly checked and tested all the code. In Chrome Developer tools, I can see that jQuery is properly adding and removing the class at the correct times, but the CSS styling doesn't seem to take effect.

$(document).ready(function() {
    
    var stickyNavTop = $('nav').offset().top;
    
    var stickyNav = function() {
        
        var scrollTop = $(window).scrollTop();
        
        if (scrollTop > stickyNavTop) {
            
            $('nav').addClass('sticky');
            
        } else {
            
            $('nav').removeClass('sticky');
        
        }
    };
    
    stickyNav();
    
    $(window).scroll(function() {
        stickyNav();
    });
});
* {
    margin: 0;
    padding: 0;
    font-family: "Helvetice Neue", sans-serif;
}

@font-face {
    font-family: "Helvetica Neue";
    src: url("../fonts/HelveticaNeue.otf");
}

html, body {
    width: 100%;
    height: 100%;
}

div#container {
    width: 100%;
    height: 100%;
}

div#content {
    width: 100%;
    height: 100%;
}

section#main-bg {
    width: 100%;
    height: 100%;
}

#main-bg img {
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: -9999; /* always on bottom */
}

nav {
    width: 100%;
    height: 60px;
    bottom: -60px;
    background-color: #333333;
}

/* nav */ .sticky {
    position: fixed;
}

nav ul {
    float: right;
}

nav ul li {
    float: left;
    margin-left: 40px;
    list-style: none;
}

nav ul li a {
    text-decoration: none;
    color: white;
    padding: 20px;
    line-height: 60px;
}

div#content {
    width: 100%;
    height: 2000px;
    background-color: #dedede;
    bottom: 0;
}
<!DOCTYPE html>
<html>
    <head>

        <title>Josh Murray | My Personal Page</title>    
        <meta name="viewport" content="width=device-width, height=device-width, user-scalable=no, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="css/main_styles.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="scripts/homemadeSticky.js"></script>
    
    </head>
    
    <body>
        
        <div id="container">
                
                <section role="banner" id="main-bg">
                    
                    <!-- this is where the full screen image will be -->
                    
                    <img src="img/bg.jpg">
                    
                </section>
                
                <nav>
                    
                    <ul>
                        
                        <li><a href="#">Home</a></li>
                        <li><a href="#">Products</a></li>
                        <li><a href="#">About</a></li>
                        <li><a href="#">Contact</a></li>
                        
                    </ul>
                    
                </nav>
                
                <div id="content">
                    
                    <!-- content in here -->
                    
                </div>
            
        </div>
        
    </body>

</html>

Your assistance is greatly appreciated. Thank you.

Answer №1

Adjust your css to fix the position with the following code:

.sticky {
    position: fixed;
    top: 0;
}

$(document).ready(function() {
    
    var stickyNavTop = $('nav').offset().top;
    
    var stickyNav = function() {
        
        var scrollTop = $(window).scrollTop();
        
        if (scrollTop > stickyNavTop) {
            
            $('nav').addClass('sticky');
            
        } else {
            
            $('nav').removeClass('sticky');
        
        }
    };
    
    stickyNav();
    
    $(window).scroll(function() {
        stickyNav();
    });
});
* {
    margin: 0;
    padding: 0;
    font-family: "Helvetice Neue", sans-serif;
}

@font-face {
    font-family: "Helvetica Neue";
    src: url("../fonts/HelveticaNeue.otf");
}

html, body {
    width: 100%;
    height: 100%;
}

div#container {
    width: 100%;
    height: 100%;
}

div#content {
    width: 100%;
    height: 100%;
}

section#main-bg {
    width: 100%;
    height: 100%;
}

#main-bg img {
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: -9999; /* always on bottom */
}

nav {
    width: 100%;
    height: 60px;
    bottom: -60px;
    background-color: #333333;
}

/* nav */ .sticky {
    position: fixed; top: 0;
}

nav ul {
    float: right;
}

nav ul li {
    float: left;
    margin-left: 40px;
    list-style: none;
}

nav ul li a {
    text-decoration: none;
    color: white;
    padding: 20px;
    line-height: 60px;
}

div#content {
    width: 100%;
    height: 2000px;
    background-color: #dedede;
    bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
    <head>

        <title>Josh Murray | My Personal Page</title>    
        <meta name="viewport" content="width=device-width, height=device-width, user-scalable=no, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="css/main_styles.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="scripts/homemadeSticky.js"></script>
    
    </head>
    
    <body>
        
        <div id="container">
                
                <section role="banner" id="main-bg">
                    
                    <!-- this is where the full screen image will be -->
                    
                    <img src="img/bg.jpg">
                    
                </section>
                
                <nav>
                    
                    <ul>
                        
                        <li><a href="#">Home</a></li>
                        <li><a href="#">Products</a></li>
                        <li><a href="#">About</a></li>
                        <li><a href="#">Contact</a></li>
                        
                    </ul>
                    
                </nav>
                
                <div id="content">
                    
                    <!-- content in here -->
                    
                </div>
            
        </div>
        
    </body>

</html>

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

Is there a way to adjust the state value in Pinia within a Vue3 component test, and have an impact on the component?

When testing the component using pinia with vue-test-utils, I encountered difficulty in modifying the state value stored in pinia. Despite trying multiple methods, I was unable to achieve the desired result. The original component and store files are provi ...

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

What steps can be taken to update the ID's of <tr> and <td> elements within a table after deleting a row?

I am working on a dynamic table with 5 rows, each row containing 3 columns - partNO, quantity, and a delete button. Each row is assigned a unique ID for identification purposes. If a user deletes the second row, I want the IDs of the remaining rows to be ...

How can you retrieve the current user in express.js when incorporating socket.io?

I have a web app using the express framework and socket.io for real-time chat. I am trying to get the current user's username and create a room with them in it, but I am struggling to retrieve the user info when socket.on('connection') is ca ...

JSP - Submitting a form through a link click: A complete guide

I am having an issue with submitting a form when clicking on a link. Despite my attempts, the default action is not being prevented and I keep getting the error message: HTTP Status 405 - Request method 'POST' not supported. Here's what I ha ...

Struggling to increment the badge counter in a React Typescript project

I'm a bit unsure about where to apply the count in my Badge Component. The displayValue should include the count, but I'm struggling with how to implement it. UPDATE: The counter is now in place, but when I decrease the count and it reaches 0, t ...

Can someone please help me figure out why the "setInterval" function in my script isn't functioning as expected?

I've been experimenting with controlling the refresh rate of drawn objects in a canvas using JavaScript. Even after going through the tutorials and examples on w3.school, I'm still unsure why the "setInterval" function is not executing the "gener ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

Tips on displaying JSON data in the browser console using console.log for API consumption

I'm having trouble creating an api to output data parsed from an xml file. When I console.log the necessary data, it shows up fine, but when I try to display it in the browser, I only get an empty array. Any suggestions on what could be causing this i ...

Three.js combined with Ember.js

I've been brainstorming ways to merge Ember.js with Three.js. My goal is to render multiple elements, manage the data with Ember.js bindings and general pub/sub handling, while also being able to manipulate the views/elements with three.js using THREE ...

Are cookies with the http_only attribute included in requests made through AJAX?

While browsing the web, I came across this interesting link However, it also mentioned at the bottom that This information may no longer be current. This got me thinking, can http_only cookies be transmitted with AJAX? And can AJAX responses set http_only ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

Having an issue with my JavaScript burger menu not functioning properly

I'm really struggling to figure out why my code isn't working. I've checked and rechecked all the links, and everything seems correct. Could it possibly be because the code is outdated? I've been stuck on this for two days now and can&a ...

What are some creative ways to incorporate images into SVG paths?

Check out my JSFiddle here. I'm attempting to position this image in the center of my arc. My initial thought was to use .attr("fill","url('somePicture')"), but so far, no luck with that approach. const width = 700; const height = 600; con ...

Issue with handling promise rejection of type error in node.js

Whenever I try running node server.js in Node.js, an error message pops up saying 'Cannot read property 'length' of undefined'. Despite installing all the necessary libraries (such as request) and browsing through various related posts ...

What is the process for utilizing an Angular service within a view expression?

Angular guidelines suggest utilizing Angular services and expressions: It is recommended to use services like $window and $location in functions called from expressions. These services offer a way to access global variables that can be easily mocked. - ...

Simply tap on any part of the row to select the checkbox and bring attention to it?

Is there a way to make rows in a table selectable by clicking anywhere on the row? I have a script that displays checkboxes next to each result from a MySQL database, but I want users to be able to click anywhere on the row to select it and highlight the e ...

Divergent Bootstrap layouts for different devices

https://i.sstatic.net/g1YeJ.png I am working on creating a layout where I want to display certain content differently based on whether the user is viewing it on a mobile or desktop device. The current approach I have taken involves duplicating some divs ...

Troubleshooting problems with ASP pages in WebMatrix 2

Every time I try to update my website and add new pages using WebMatrix 2, I encounter errors in my asp pages such as: "This document type is not supported. IntelliSense and validation for this document type will be based on HTML 5." The issue seems to b ...

Code for the AJAX function is not being activated by the FadeOut effect

Currently, I am delving into the realm of JQuery, attempting to incorporate Ajax queried data from a text file into a div element. However, I am facing an issue where the program fails to function as intended when the AJAX code is added and the function is ...