Require a secondary navigation bar to remain fixed below the primary navigation bar as the user scrolls upwards

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

Is there a way to make this second nav bar stick under the main nav bar when the user scrolls up? Currently, it sticks behind the main nav bar. I have attempted a few solutions, but I struggle with JavaScript. Here is the code for the main nav bar and the second one:

Main nav bar HTML

   <nav id="navigation_elements">
        <div class="row">
            <!--Start of Main Navigation-->
            <div id="main_nav">
                <div class="menu-main-menu-container"><ul id="menu-main-menu" class="menu"><li id="menu-item-529" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-63 current_page_item menu-item-529"><a href="./" aria-current="page">Home</a></li>
    <li id="menu-item-721" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-721"><a href="./how-does-pawn-work/">How Does a Pawn Loan Work?</a></li>
    <li id="menu-item-728" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-728"><a href="./contact-us/">Contact Us</a></li>
    <li id="menu-item-720" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-720"><a href="./jewelry/">Jewelry</a></li>
    <li id="menu-item-727" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-727"><a href="./car-audio-and-accessories/">Car Audio and Accessories</a></li>
    <li id="menu-item-724" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-724"><a href="./consumer-electronics/">Consumer Electronics</a></li>
    <li id="menu-item-726" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-726"><a href="./tools/">Tools</a></li>
    </ul></div>     </div><!--End of Main Navigation-->
                </div>
    </nav>

HTML for the second nav bar

<div id="navbar1">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>

CSS

<style>
/* Style the navbar */
#navbar1 {
  overflow: hidden;
  background-color: #333;
}

/* Navbar links */
#navbar1 a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}

/* Page content */
.content {
  padding: 16px;
}

/* The sticky class is added to the navbar with JS when it reaches its scroll position */
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

/* Add some top padding to the page content to prevent sudden quick movement (as the navigation bar gets a new position at the top of the page (position:fixed and top:0) */
.sticky + .content {
  padding-top: 60px;
}

</style>

Javascript

<script>
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};

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

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

// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar1.classList.add("sticky")
  } else {
    navbar1.classList.remove("sticky");
  }
}
</script>

Answer №1

After gaining a clear understanding of your requirements, I have crafted a customized example inspired by W3Schools. The objective is to implement a fixed main navigation with properties such as position: fixed;, top: 0;, and height: 45px;, ensuring it remains anchored at the top of the viewport.

To maintain proper margins, a container element has been included with the style margin-top: 45px;.

Following the container, your banner content and styling are presented, replicating the layout showcased on W3Schools for visual reference.

Subsequently, the implementation involves inserting a sticky navigation element after the banner. The .sticky class should also incorporate the property top: 45px;.

Furthermore, adjustments have been made to the JavaScript functionality to prevent content from overlapping with the main navigation. The condition

window.pageYOffset >= sticky - height
addresses this issue. Additionally, an error in the initial JavaScript code was corrected: var sticky = navbar1.offsetTop; was amended to var sticky = navbar.offsetTop;.

If you require further guidance on integrating this solution into your codebase, I am available to assist you.

To visualize the cohesive functionality of these elements, a comprehensive code example is provided below:

(preformatted code examples displayed 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

My Javascript code initiates an AJAX request before any other operations are executed

I am facing an issue with my Flask application and client-side JavaScript. I am trying to send an object using AJAX from my JavaScript to the Flask application running on the server side. However, the AJAX request is being sent before the rest of my JavaSc ...

struggling to access $scope variable in MVC partial view using AngularJS

I am looking to include a partial in my main content. This snippet is from my _layout.cshtml page. <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.T ...

Create a Grid-Item-List with a custom arrangement, utilizing techniques like flex-box to achieve the desired layout

Struggling to create a unique grid-list that looks great on both desktop and mobile devices. Any tips or solutions would be greatly appreciated! I need a list (left image) with a special layout, which can be achieved through nested grids. However, I want ...

"Adding an Image within a Textbox Using Ext JS: A Step-by-Step

How can I add a search image inside a textbox created with the following code? I have created a table with a footer, and within one of the textboxes in the table, I want to include a search button that will call another function when clicked. However, desp ...

What is it about this JavaScript code that IE8 seems to have a problem with?

Encountered an error in IE8 that has been causing trouble for me SCRIPT65535: Unexpected call to method or property access. load-scripts.php, line 4 character 25690 After removing a .js file from the code, the error disappeared. By commenting out f ...

Addressing Layout Problems When I Enlarge the Browser Width

My website is www.adventureswithross.com When the device width is larger than 601px, I have specific requirements: I need the menu and custom header to be seamlessly connected without any spacing in between. To address the issue of space above the custo ...

HTML - Toggle visibility of div using display property

I'm currently working on implementing a show and hide functionality for a div. I followed a tutorial from a website called w3schools, but the way they implemented it is different from what I'm looking to achieve. In their example, the div is init ...

Stop the reoccurring action for a jQuery plugin by using the clearInterval function

Having a difficulty with clearing the interval inside a jQuery plugin. Below is a simplified code snippet. When attempting to run the following in the Firefox console: $('.banner').pluginName().stop() the console keeps logging `console.log(1)`. ...

The functionality of HTML5 Camera is experiencing issues while being used with Tomcat7

My Angular2 project includes HTML5 camera access functionality. I launch the project using Angular CLI (ng serve), which starts the web container for testing purposes. When trying to access the camera, the browser prompts me for permission. Once granted, e ...

The attribute 'nameFormControl' is not a valid property on the 'ContactComponent' component

Greetings, StackOverflow community! I'm currently working on an Angular + Node app and I've run into a major problem related to forms and validators in Material Angular. Right now, I'm facing an issue where the HTML component is not recogn ...

Is there a way to stop the navbar from covering the title?

Looking for help with customizing my navbar. At the moment, it resembles image one but I'm aiming for the appearance of image two. Any suggestions on how to achieve this? Is it a CSS modification that needs to be made? /* Nav Bar*/ .navbar-brand{ ...

The value remains constant until the second button is pressed

I have a button that increments the value of an item. <Button bsStyle="info" bsSize="lg" onClick={this.addItem}> addItem: addItem: function() { this.setState({ towelCount: this.state.towelCount - 2, koalaCount: this.state.koalaCount + 2 ...

Removing various data entries based on timestamp and additional fields in Firebase Firestore

I stumbled upon a similar query before. Being new to coding, I am attempting to remove all documents in the "users" collection that are older than 1 month and not marked as premium. The deletion criteria involve checking if the "user_online" field is at le ...

Encountering a 400 error while trying to implement file upload feature in Spring AngularJS -

Whenever I attempt to upload a file using Spring and AngularJS, I keep encountering the dreaded 400 Bad Request error: > error: "Bad Request" > exception: "org.springframework.web.multipart.support.MissingServletRequestPartException" > message: " ...

Align Text with Icon Using FontAwesome

Hey, I'm having a bit of trouble with something simple and it's driving me crazy. All I want to do is center the text vertically next to a FontAwesome icon. However, no matter what I try, I just can't seem to get it to work. I've looke ...

The art of jQuery Accordion and Tab Design

After researching, I attempted to integrate a jQueryUI accordion into jQueryUI tabs. Despite many success stories, I encountered challenges. Upon initializing the accordion inside the tabs' 'show' event, I only saw two half-styled tab header ...

prevent clicking on the div element

I have been attempting for quite some time to disable a click on a specific div element. The purpose behind this is to prevent unauthorized users from triggering certain events that are activated when the div is clicked. In my previous attempt shown below ...

Having difficulty retrieving the value of the final <th> element within a table or list

I am encountering an issue where I cannot retrieve the value of the last item and update the next item accordingly. I have attempted using :last-child, but it does not provide the desired values. if ($("tbody").children().length == 0) { var ...

Incorporating URL parameters into an HTML form using JavaScript or jQuery

I need to pass variables in the URL to populate an HTML and Liquid form and then submit it. Here is an example URL: http://www.example.com/[email protected] &customer_password=123456 I came across this question which is somewhat related to what ...

Trouble aligning a div at the center within another div using margin auto

I am facing an issue with centering a div horizontally inside another div. Here is my HTML code: .block { padding: 0px 20px; max-width: 820px; margin: 0 auto; background-color: #ff0; } .container { margin: 0 auto; display: inline-block; bac ...