Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the screen and adjusts dynamically based on the window size. Instead of setting a fixed point for the navbar to stick after scrolling a certain distance, I need a Javascript function that triggers the sticking effect when reaching the bottom of any element.

Here is the HTML:


    <header>
  <img src="https://upload.wikimedia.org/wikipedia/commons/d/de/Mount_Shuksan,_Picture_Lake_(2362739742).jpg" alt="">
  </header>

  <nav id = "nav_bar">
      <ul class = "navbar-list">
          <li>
              <a href="">link1</a>
          </li>
          <li class="dropdown">
              <a href="#" class="dropbtn">link2</a>
                  <div class="dropdown-content">
                      <a href="#">link 1</a>
                      <a href="#">link 2</a>
                      <a href="#">link 3</a>
                      <a href="">link 4</a>
                  </div>
          </li>
          <li>
              <a href="">link 3</a>
          </li>
          <li>
              <a href="">link4</a>
          </li>
      </ul>
  </nav>

<body>

<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>

<p>
  Lorem ipsum dolor...

CSS:

...

This updated version also includes a sample image overlapping the header for better visualization: codepen.io.

Answer №1

Just like with the Tutorial Codepen, all you need to do is update the selectors in the example to match your own.

Give this a try:

var  mn = $("#nav_bar");
    mns = "navbar-fixed";
    hdr = $('header').height();

$(window).scroll(function() {
  if( $(this).scrollTop() > hdr ) {
    mn.addClass(mns);
  } else {
    mn.removeClass(mns);
  }
});

Check out the codepen here


Important: When setting your navbar to sticky, keep in mind that the space where the navbar was will be removed. This may result in the navbar overlapping with your first line of text. To avoid this, remember to add padding to your header equal to the height of your navbar. You can do this in your javascript as well.

You can either add a class with this padding or manually adjust it. Here are some examples:

$('header').addClass("extraPadding"); // Create the extraPadding class

or

$('header').css("padding-bottom", "40"); // Use 40 as the height of your navbar

Answer №2

Here is an example

var menu_top_offset = $('#menu').offset().top;

$(window).scroll(function() {
  if ($(this).scrollTop() > menu_top_offset) {
      $('#menu').addClass('fixed');
  } else {
    $('#menu').removeClass('fixed');
  }
});
body {
  margin: 0px;
}
header {
  margin: 0 auto;
  /*position: fixed;*/
  top: 0;
}
section{background:#fff}
img {
  max-width: 100%;
  text-align: center;
  top: 0;
  display: block;
}
.navbar-fixed {
  top: 0;
  z-index: 100;
  position: fixed;
  width: 100%;
}
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}
li {
  float: left;
}
li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
li a:hover,
.dropdown:hover .dropbtn{
  background-color: blue;
}
li.dropdown {
  display: inline-block;
}
.dropdown-content {
  display: none;
  position: absolute;
  background-color: yellow;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
.dropdown-content a:hover {
  background-color: #f1f1f1
}
.dropdown:hover .dropdown-content {
  display: block;
}
.fixed{
  position:fixed;
  top:0;
  width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header>
  <img src="https://upload.wikimedia.org/wikipedia/commons/d/de/Mount_Shuksan,_Picture_Lake_(2362739742).jpg" alt="">
  </header>

<nav id="menu">
  <ul class="navbar-list">
    <li>
      <a href="">link1</a>
    </li>
    <li class="dropdown">
      <a href="#" class="dropbtn">link2</a>
      <div class="dropdown-content">
        <a href="#">link 1</a>
        <a href="#">link 2</a>
        <a href="#">link 3</a>
        <a href="">link 4</a>
      </div>
    </li>
    <li>
      <a href="">link 3</a>
    </li>
    <li>
      <a href="">link4</a>
    </li>
  </ul>
</nav>;
 <p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>

  <p>
    Lorem ipsum dolor sit...etc...
  </p>

Answer №3

let navigation = $('.adjustlink');
    let position = navigation.offset().top;

    $(window).scroll(function (){
        let fixPosition = ($(this).scrollTop() > position) ? true : false;
        navigation.toggleClass("fixed-navigation", fixPosition);
    });

Here is a helpful resource for you JSFiddle Example

Answer №4

I believe the solution you are aiming for is this. Hopefully, it will assist you. Click on the Run code snippet button to see it in action.

To achieve the desired effect of fixing an element while scrolling, you need to add a class called fixed when you reach that specific element and remove it when scrolling back up.

var navBarOffset = $('#nav_bar').offset().top;

$(window).scroll(function() {
  var navBar= $('#nav_bar');
  var scroll = $(window).scrollTop();

  if (scroll >= navBarOffset ) {
    navBar.addClass('fixed');
  } else {
    navBar.removeClass('fixed');
  }
});
body {
  margin: 0px;
}
header {
  margin: 0 auto;
  /*position: fixed;*/
  top: 0;
}
.fixed {
  position: fixed;
  top:0; 
  left:0;
  width: 100%; 
}
img {
  max-width: 100%;
  text-align: center;
  top: 0;
  display: block;
}
.navbar-fixed {
  top: 0;
  z-index: 100;
  position: fixed;
  width: 100%;
}
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}
li {
  float: left;
}
li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}
li.dropdown {
  display: inline-block;
}
.dropdown-content {
  display: none;
  position: absolute;
  background-color: green;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
.dropdown-content a:hover {
  background-color: #f1f1f1
}
.dropdown:hover .dropdown-content {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <img src="https://upload.wikimedia.org/wikipedia/commons/d/de/Mount_Shuksan,_Picture_Lake_(2362739742).jpg" alt="">
</header>

<nav id="nav_bar">
  <ul class="navbar-list">
    <li>
      <a href="">link1</a>
    </li>
    <li class="dropdown">
      <a href="#" class="dropbtn">link2</a>
      <div class="dropdown-content">
        <a href="#">link 1</a>
        <a href="#">link 2</a>
        <a href="#">link 3</a>
        <a href="">link 4</a>
      </div>
    </li>
    <li>
      <a href="">link 3</a>
    </li>
    <li>
      <a href="">link4</a>
    </li>
  </ul>
</nav>

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 it possible to set up an automatic redirection to the Identity Provider sign-in page when accessing a protected page in Next.js using Auth.js?

Currently in the process of developing a web platform utilizing [email protected] and Auth.js([email protected]). The provider has been configured with the given code, allowing successful signing in using the "Sign in" button. auth.ts import Ne ...

Refreshing website with personalized retrieved information

My goal is to populate a tab with specific data from a button click using the unique_id. However, I am encountering an issue where I want the tab to display the corresponding variable without having to refresh the page. Despite searching for solutions on ...

I'm running into some issues when it comes to uploading and launching my website through cPanel on Namecheap

After adjusting the permissions of all HTML and CSS files to 0755 and image files to 0644 in the public_html folder, I am encountering difficulties publishing the site. It seems like I have hit a roadblock and unsure about what steps to take next... ...

What are the steps for skipping, sorting, and limiting with dynamoose?

After being familiar with MongoDB and mongoose, I am now exploring dynamoose for my app. In order to replicate the below-shown mongoose query using dynamoose, how can I write it? Specifically, I want to achieve the same functionality as the following mong ...

Assign the state to a new object by preserving matching values from the previous state

In my current state, I have an object structured like this: stateObject = {0: 400, 1: 500, 2: 600} Whenever my component rerenders on componentWillUpdate, an additional column is added carrying over the value at key index 0 (400). My goal is to update th ...

Filtering data in a table using Jquery based on specific columns and headers

To retrieve a price value from an HTML table based on a specific column and header, follow these steps: Here is how the table is structured: The HTML code appears as follows: <input id="search_height" placeholder="height..."> <input id= ...

AngularJS - Dynamically change the placeholder value

<md-input-container class="md-block hide-error-space" flex="25"> <input required name="password" ng-model="password"> </md-input-container> Here is a form field where the user can enter their password. <md-input-container md-no-float ...

The route parameters seem to be malfunctioning when using the Google Maps Directions API

Currently, I am attempting to transfer the latitude and longitude of a location from one HTML file to another using the $routeParams feature. In the second HTML file, I utilized the Google Maps directions API to display the directions from the source lati ...

Tips for positioning a delete button at the start of the row I am transferring to a different table

Displayed below are the contents of the initial table. <% for(int i = 0; i < result.length; i++) { %> <tr id='player-listing-<%=i %>'> <td style="vertical-align: top;"><button onclick="myFunction2(<%=i%> ...

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

Troubleshooting: Why is Jquery unable to retrieve image height?

Having trouble using jQuery to find the actual height of the first image nested within a container. I can access the src attribute but not the height. Any suggestions on how to get the accurate height? Is it necessary to retrieve heights via CSS? Unfortu ...

Issues arise when submitting the form on a web page with an MVC 4 partial view, causing the page

Scenario: I am currently working on a C#/MVC 4 project where I have a view that includes a partial view. The main view consists of a form with a submit button, and the partial view is initially hidden but can be displayed by selecting a checkbox. Problem: ...

Obtain the child's identification number and include it in the parent element as an ARIA

I need assistance with a JavaScript (or jQuery) function to dynamically add an 'aria-labelledby' attribute to parent <figure> elements based on the ID of the <figcaption>. I have multiple images and captions set up in <figure>&l ...

Error in HTML: The AgGrid component is missing the required 'col' attribute

Initially, I worked with the 2.3.5 version of Ag-Grid which had a "col" attribute showing the relative index of the column for each cell element. The "row" attribute still remains unchanged. However, after upgrading to version 4.0.5, the "col" attribute ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

What is the best way to transfer an id from JavaScript to Rails while utilizing ajax?

Is there a way to call a rail route and pass in an ID from javascript? I have recently started using rails routes within my application, even in js. The current code I am using is: # app/assets/javascript/verifying_link.js $.ajax({ url: "/verify_link/ ...

What is the best method to retrieve the country name from a world map using D3.js?

I'm trying to figure out how to retrieve the country name from a click event on the D3 world map. Despite inspecting the DOM, I can't quite understand how the country's name, code, or population is associated with the map. The template for ...

What is the best way to insert a triangle shape to the bottom of a div with an opacity level set at 0.2

https://i.stack.imgur.com/sqZpM.png I've been trying to create something similar, but my triangle keeps overlapping with the background in the next section. I've already spent 3 hours on it. Any help would be greatly appreciated. Check out my c ...

How can serial numbers be sorted using a JavaScript If Statement based on 2 criteria?

I'm currently enrolled in a JavaScript coding course where I am tackling a task involving validating serial numbers. The requirement is to check if a serial number is valid and then add it to an array to store all the valid serial numbers. The criteri ...

Looking to invoke the parent function from a jQuery iframe dialog?

1) Frame.jsp <div id="existingEndorsement" style="font-size:12px; height:200px !important; display: none;" > <iframe id="existingEndorsementFrame" width="410" height="200"></iframe> </div> 2) ExistingEndorsement.jsp function ...