Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website.

I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top.

Despite my efforts, I have been unable to achieve the desired result.

Answer №1

I successfully implemented this feature using a CSS class and a small snippet of JavaScript to activate the class.

The concept revolves around comparing the position of the element with the current scroll of the viewport.

For a demonstration, you can visit my CodePen example: http://codepen.io/giacomofurlan/pen/hcfkE

To delve deeper into the specifics, check out my extended explanation here:

Here is the key part - the JavaScript controller (identifying nav#menu as our sticky menu):

(function ($) {
    "use strict";

    var menuPosition = function () {
        var nav = $("nav#menu"),
            height = nav.height(),
            windowHeight = $(window).height();

        if ($(window).scrollTop() > (windowHeight - height)) {
            nav.addClass('fixed');
        } else {
            nav.removeClass('fixed');
        }
    };

    menuPosition();
    $(document).scroll(menuPosition);
}(jQuery));

Additionally, here is the accompanying CSS class:

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

Answer №2

Are you looking for this solution? If yes, then jQuery can help you achieve it. Don't forget to search on Google before posting anything; there are numerous tutorials available.

$(document).ready(function() 
{
window.holdOffset = $('#sticky_navigation').offset().top;
$(window).scroll(function() 
{
 sticky_navigation();
});
});

function sticky_navigation()
{
var scroll_top = $(window).scrollTop(); 
if (scroll_top > holdOffset)  
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 }); 
else 
$('#sticky_navigation').css({ 'position': 'relative' });    
};
body
{
margin:0px;
}

p
{
margin-left:100px;
margin-right:100px;
}

#my_logo 
{
font-size:80px;
}


#sticky_navigation_wrapper 
{
width:100%;
height:50px; 
}

#sticky_navigation 
{
width:100%; 
height:50px; 
background:black; 
}

#sticky_navigation ul 
{
list-style:none; 
margin:0; 
padding:5px; 
}


#sticky_navigation ul li a 
{
display:block; 
float:left; 
margin:0 0 0 5px; 
padding:0 20px; 
height:40px; 
font-size:24px; 
color:#ddd; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>

<link href="demo.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="sticky-navigation.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>


</head>
<body>

<div id="demo_top_wrapper">

<div id="demo_top">
<div class="demo_container">
<div id="my_logo">Site Logo</div>
</div>
</div>

<div id="sticky_navigation_wrapper">
<div id="sticky_navigation">
<div class="demo_container">
<ul>
<li><a href="#" class="selected">Link #1</a></li>
<li><a href="#">Link #2</a></li>
<li><a href="#">Link #3</a></li>
</ul>
</div>
</div>
</div>


</div>

<section id="main">

<div id="content">

<p><strong>Scroll down to see this navigation menu sticking to the top of the page.</strong></p>

<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit...
(Additional text and code content here)
...
</p>

</div>

</section>

<script type="text/javascript" src="myscript.js"></script>
</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

"Encountered an issue with combining multiple meshes that share the same geometry but have

I wrote a loop that generates multiple Mesh objects with various geometries, where each mesh corresponds to a specific texture: var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize); var geometry = new THREE.Geometry(); for( var i = 0; i ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

jQuery-UI dialog issue: Unable to convert JavaScript argument occurs during $.ajax POST request

I am currently working with the jQuery-UI dialog and attempting to utilize AJAX to send data from my dialog form when the send button is clicked. I have found that both the $('').submit() and $('').load(url) methods are functional for m ...

What is causing the issue with the code `exports = { z: function() {} };` not functioning as intended?

Script A exports = { z: function() { console.log('aZ'); } }; Script Main require('./a').z(); // error Have you ever wondered why require('./a') ends up returning an empty object? ...

Refresh the current page in Next.js when a tab is clicked

I am currently working on a Next.js page located at /product While on the /product page, I want to be able to refresh the same page when I click on the product link in the top banner (navbar) that takes me back to /product. Is there a way to achieve this ...

Stripping CSS prefixes upon file initialization

When developing my application, I have a process in place where I load CSS files on the back-end using Express.JS and then transmit them to the front-end. However, before sending the CSS code to the front-end, I need to: Identify the user's browser; ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

What is the method for extracting an entire space-separated string into a PHP variable from HTML options?

When the select tag fetches options from a MySQL database and assigns a value to a PHP variable for echoing, only the first part of the text is displayed. For example : Option: Vijay Sharma Echo Output: Vijay <select name="facultyname" oncha ...

A comprehensive guide on troubleshooting the toggleComplete functionality for React Todo applications

When you click on an item in the to-do list, it should show a strikethrough to indicate completion. However, when I try clicking on an item, nothing happens. Here is my toggleComplete function and where I am attempting to implement it: class ToDoForm exten ...

Unable to reinitialize the DataTable using Angular Datatable

I've been working on an Angular application that has a simple CRUD functionality. Initially, I tested my data with a static HTML table and everything was functioning as expected. However, I decided to implement a data table framework called Angular da ...

What is the best way to retrieve the current CSS width of a Vue component within a flexbox layout grid after it has been modified?

There's something about this Vue lifecycle that has me scratching my head. Let me simplify it as best I can. I've got a custom button component whose size is controlled by a flex grid container setup like this: <template> < ...

Adjust the slide count accordingly when navigating to a particular item within the Bootstrap 3 Carousel

I made adjustments to the standard Bootstrap 3 Carousel so that it can navigate to a specific slide when the URL matches #. Although this feature is working, I am facing an issue with my pager-text not updating correctly when jumping to a specific slide. T ...

Is the HTML encoded character displaying strangely due to spacing issues?

I'm having trouble creating a link with a right chevron that has a larger font size. The issue I'm facing is that the right chevron appears to have excessive top margin, causing a significant gap between it and the line above. Additionally, I wa ...

Is there a AngularJS alternative to jQuery's .load() method?

How can this be achieved in AngularJS? angular.element('#container').load('http://google.com'); Important: This involves loading content from an external domain. ...

What is the process to obtain the child theme URL in WordPress?

Currently, I am working on creating a child theme for my WordPress website. I have successfully uploaded the assets folder which contains both CSS and JavaScript files. This child theme will be completely customized to suit my needs. Within the <head&g ...

Navigating Checkbox in Active Choice Reactive Reference Parameter on Jenkins

I attempted to configure an active choice reactive reference parameter using the instructions outlined in this guide: Here is the code for the reactive reference parameter: service_tier_map = [ "web": [ ["service_name": "use ...

Generate various shapes using a loop

Hello, I'm currently working on creating multiple forms using a loop that is generated from dynamic elements fetched from the database. However, I believe there might be some issues in my approach. Below is what I have tried so far. While it works to ...

Angular animations are failing to function in the Visual Studio 2017 template

I am facing a challenge with incorporating animations in Angular 2 using Visual Studio 2017. I believe there must be a simple solution that I am overlooking at the moment. My goal is to animate certain elements and I have been testing the animations by tri ...

Nuxt.js transition issue: How to fix transitions not working

LOGIC: The pages/account.vue file consists of two child components, components/beforeLogin and components/afterLogin. The inclusion of child components is based on a conditional check within pages/account.vue using a string result ('x') stored in ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...