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

What is the process for manually looping an HTML5 video on iOS 4.3/5?

I'm facing an issue with a video that has specific segments I need to be looped. The problem arises on iOS 5, where after updating videoElem.currentTime for the third time, mobile Safari stops recognizing this attribute correctly. Interestingly, on i ...

Using only HTML, I have created a collapsible accordion in Angular without the need for JS code. However, when I click the button, nothing happens. Can you help me resolve

I am attempting to add an Accordion button to my website using the HTML code provided below. I am currently incorporating this in a very basic manner, without any utilization of javascript code, within this example of accordion snippet. When the button i ...

Javascript recursive function calling itself

I've been struggling with the logic in my code and it seems like I've been staring at it for too long to spot the issue. A strange recursion occurs when this piece of code runs after a 30-second timeout, resulting in multiple GET requests to rese ...

Troubleshooting overlap problem between Skrollr and SlickNav

I successfully implemented Skrollr to fix images, similar to this example: Additionally, I am utilizing Slicknav for the menu functionality. However, I encountered an issue where the menu opens behind the fixed "parallax" image. Despite trying various ap ...

Internet Explorer is unable to recognize the .less file format

I have created a less file that works perfectly in Chrome and Firefox, but it is not being recognized in IE 9. Does anyone have suggestions on how to make it run in IE 9.0? Below is a sample of the CSS code: @import "../core/variables.less"; @import "Mi ...

Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below: <template> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> < ...

Included adaptable background-images in the upload

Recently, I developed a RoR based app/website that allows clients to upload their own background image to the cover page. Although the current setup works well with a single image, I am aiming to enhance the site's responsiveness by enabling clients t ...

Retrieve the value of a property in a JavaScript object by specifying a dynamic key for the property

As I work on my current project, I find myself immersed in a world of SVG animations. The challenge lies in triggering these animations as the user scrolls down to view the SVGs. To address this, I took the approach of creating functions for each Snap.SVG ...

Retrieve the input value from a Bootstrap Form Input

When using a Bootstrap Form Input to allow the user to enter text, I am wondering how to save that text and use it as a parameter in a function. Below is the HTML snippet I have: <!--Directory Input Form--> <div class="row"> <div class= ...

Leveraging Web Services in Outlook Mail Add-On

I am facing a challenge with an Outlook Mail Add-In that I need assistance with. Using an Office 365 developer account, the Mail Add-In displays online in a browser as shown in this screenshot: https://i.stack.imgur.com/ZQ9qt.png My objective is to trigge ...

Double dragenter events triggered before dragleave in HTML5 drag and drop functionality

Currently, I'm researching HTML5 Drag and Drop functionality by using this resource. However, I've encountered an issue with the dragenter event that seems to fire twice for child elements before the dragleave event. Because of this, the dashed b ...

Guidance on loading JSON array information into highcharts using AngularJS

I am working on a project in Play Framework (play-java) where I need to display a bar graph using Highcharts. The Java API returns data in JSON format with a field called 'name' containing values like 'Data', 'Gadgets', ' ...

Guide on encrypting data on the server with PHP and decrypting it on the client side using JavaScript

I'm currently developing a training website with PHP and I am looking to share my training resources securely without worrying about copyright issues. My plan is to encrypt the documents on the server before sending them, and then have them decrypted ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

Tips for transferring information to an input field's value

There's an input box with an empty value that needs to be filled with data. <input type="text" value="" class="box"> $('.skills-tags').on('click', function(){ var value = $(".skills-tags").val(); $('.label-pr ...

Adding dots between page numbers when using ReactJS/Javascript Pagination can be achieved by implementing a specific method

I have created a pagination component using React JS. Currently, it only displays all the page numbers, but I want it to show dots when there are more than 8 total pages. Here's how I envision it: c. When total is less than 9 pages: Page 1 selecte ...

The AngularJS component materializes almost instantaneously

Using AngularJS, I have developed an application where a certain section of code is displayed after the page loads for a split second: <div class="col-sm-4" data-ng-repeat="user in users"> <div class="card"> ...

Exploring ways to incorporate various classes into my validate() elements using jQuery

I'm currently using the jQuery method validate to verify this particular form: <form id="emailRecover"> <div class="row light-field-container error-container"> <input type="text" id="dniPassword" name="dniPassword" requ ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

React - Unable to perform 'removeChild' on 'Node' object: The specified node cannot be removed as it is not a child of this node

I am encountering an issue in my React project with the following structure: <div className="App"> <BrowserRouter> <BasicLayout title={"test"}> <Routes> <Route path="/home&qu ...