Creating a navigation bar that stays fixed at the top of

Hey there, currently I am utilizing a combination of jquery and css to affix my navigation menu at the top when scrolled. However, the problem is that my navigation menu is positioned beneath a div with a height set in viewport units (vh). The jquery script does not seem to recognize vh as a valid measurement for height. Any ideas on how I can modify it to accept vh?

$(function(){
        $(window).scroll(function() {
            if ($(this).scrollTop() >= 290) {
                $('nav.stickynav').addClass('stickytop');
            }
            else {
                $('nav.stickynav').removeClass('stickytop');
            }
        });
    });
.stickynav.stickytop {
        position:fixed;
        top:0
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<header class="group">
    <img src="<?php echo get_bloginfo('template_directory');?>/img/es.png">
    <nav class="stickynav"><?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?></nav>
    </header>

Answer №1

Have you heard about the new feature in CSS called position: sticky? It could be really beneficial for your website as it eliminates the need for any JavaScript to make it work. However, keep in mind that since it is a relatively new addition, it may not function properly on all browsers and especially on older, outdated ones.

Answer №2

Check out the code snippet below for implementing a sticky header on your website.

$(function() {
  /* Sticky Header */
  $(window).scroll(function(){
    var sticky = $('.header'),
    scroll = $(window).scrollTop();
    if (scroll >= 100){
      sticky.addClass('fixed');
      sticky.fadeIn();
    } else {
      sticky.removeClass('fixed');
      sticky.removeAttr("style");
    }
  });
});
/* Header */

header.header {
  background: #000;
  padding: 1em;
  box-sizing: border-box;
}

header.header.fixed {
  position: fixed;
  width: 100%;
  display:none;
  top: 0px;
  left: 0px;
  z-index: 202;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header class="header">
  <div class="container">
    <nav class="main-menu" id="mm">
      <ul>
        <li><a href="#" title="#">Home</a></li>
      </ul>
    </nav>
  </div>
</header>

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

Tips for efficiently retrieving all search results from a FHIR server

When utilizing the fetchAll function on an instance of an FHIR Client (specifically HAPI FHIR server), my current goal is to gather all observations with a specific LOINC code. My understanding is that a request is made to the server prompting it to gener ...

Two adjacent divs positioned next to each other, where the right-hand div occupies the remaining space within its

I am facing a common issue with two side-by-side divs, which I usually solve without any problems by floating both divs left and adding a clear:both div after them. However, my requirements have made this problem more complicated to solve... What I would ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

Guide to implementing proportional height for an element using JQuery 3.3.1

I am currently working on dynamically setting the heights of elements with a specific class using JQuery in order to achieve a 16:10 ratio based on their width. However, I'm encountering an issue where the height doesn't seem to be applied and re ...

Displaying several column headers while filtering data in a table

Is there a way to prevent my table from printing multiple column headers each time I filter my results? For instance, after filtering, the same column headers are repeated. Here is an example of the issue: Below you can find the code snippet that demonstr ...

Ways to hide a div element when the size of the window is decreased

I need help with keeping my logo fixed on the header of my website. You can view an example of the issue here: Currently, when the window is resized to a certain height, the logo (The sun) changes position. How can I ensure that it remains fixed in place? ...

Unable to send a post request using ajax

Section of Form in home.php <div id='googleForm'> <form> <div class='item'> <label class='label'>Full Name</label> <input class=&apos ...

Experiencing difficulty when attempting to save a zip file to the C drive

I came across this code snippet on SO and decided to use it for my project. The goal is to send a simple 1.5mb zip file and save it on my C drive by making a request through Postman with the binary option enabled, sending the zip file to localhost:3012. c ...

Using Jquery to select a specific id for an input element that is a checkbox

I've been working on a snippet of jQuery code that I'd like to tailor to be more specific for one of two different input elements on my HTML page. <script> // ensure only one box is checked at a time $(document).ready(function() { ...

To complete Mocha tests, ensure to use the done() method. However, keep in mind that the resolution method is too specific. Choose either to specify a callback *or* return a Promise, but not both simultaneously

Encountering a frustrating issue with a mocha test. When I leave it alone, it freezes and displays: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. If I include `Pro ...

Selection box containing options retrieved from MySQL database dates

I am trying to populate an HTML dropdown with data from a MySQL database. I ran the query in PHPMyAdmin and it worked fine, returning one record. The entire website is connected to this MYSQL details. Here is my code:  <?php mysql_connect("loc ...

The shared hosting environment encountered an error during the Next JS build process

When I execute the command "npm run build" on my shared hosting server, it throws an error message: spawn ENOMEM. Interestingly, this command runs perfectly fine on my localhost and has been running smoothly on the hosting server for a few weeks until yest ...

Whenever my code is used within Google Sites, it triggers the opening of a new and empty tab

When using this code inside an HTML box in Google Sites, a problem arises. It seems to work perfectly fine in Internet Explorer and Chrome when saved to an HTML file. However, within Google Sites, it unexpectedly opens a new tab with no data. The code st ...

Tips for sharing data between React components without causing re-renders or relying on JSX, such as through a function within functional components

As a beginner in react, I have been struggling to find answers to this issue. I am trying to figure out how to pass data from one functional component to another in react without actually rendering the child component. Does anyone know a solution for this ...

Sending properties through the React Router to a specific component

Within my component, I have a material table that triggers a function when the edit button is clicked: //MaterialTable.js ... const handleEdit = (e, Data) => { console.log(Data) return(<EditFunction id={Data.id} />) ... The purpose of ...

Using JavaScript or JQuery, move an image from one location to another by removing it and adding

Firstly, feel free to check out the JSFiddle example My task involves moving an image with the class "Full" after a div with the class "group-of-buttons" using JavaScript. Here is the snippet of HTML code: <img src="http://i.telegraph.co.uk/multimedia ...

Tips for pausing keyframes animation on its final animation frame

Is there a way to halt my animation at the 100% keyframe? What I'm attempting to accomplish is animating these boxes so that when you click on the top one, it moves to the bottom and vice versa. Any suggestions or ideas on how to achieve this? <h ...

Turn off the "interaction failed" message in discord.js

When an interaction, such as a button click, is left unanswered, Discord will show "interaction failed" in the client. The expected action: inter.reply('stuff') My preferred action: inter.channel.send('stuff') I am not receiving an e ...

Building a custom HTML and JavaScript player to showcase multiple videos on a webpage

UPDATE: The solution has been discovered, shared, and marked as the top answer below. In the process of creating my portfolio website using HTML, CSS, and JS, I encountered a challenge regarding the addition of multiple videos on various pages. While fol ...

Silhouette as the backdrop image

There is a span element that I am using in the following way - <span class="tick"></span> This creates a decorative "tick" for a checkbox. The CSS code used for this is - input[type="checkbox"] + span > span.tick { display: block; ...