New navigation menu changes as user scrolls

I'm struggling to find a way to implement a different navigation menu that appears when the user scrolls down. I'm envisioning something similar to this example:

My goal is to have #small-menu replace #big-menu once the user starts scrolling.

Check out this JSFiddle for more information: JSFiddle

<div id="container">
  <div id="big-menu">
    <div id="big-logo">Big Logo</div>
    <div id="big-navigation">Navigation</div>
    <div id="big-search-bar">Search</div>
  </div>
  <!--<div id="small-menu"> ---Small Menu I want to replace the big menu with when user        scrolls down---
    <div id="small-logo">Small Logo</div>
    <div id="small-navigation">Navigation</div>
    <div id="small-search-bar">Search</div>
  </div>-->
<div id="content"></div>
</div>

#container {
  width: 600px;
  border: 1px solid green;
  padding: 10px;
}
#big-menu {
  height: 100px;
  border: 1px solid red;
}
#big-logo {
  width: 100px;
  height: 80px;
  border: 1px solid blue;
  margin-top: 10px;
  float: left;
}
#big-navigation {
  width: 300px;
  height: 20px;
  border: 1px solid orange;
  float: left;
  margin: 70px 0 0 10px;
}
#big-search-bar {
  width: 150px;
  height: 20px;
  border: 1px solid pink;
  float: right;
  margin: 70px 10px 0 0;
}
#small-menu {
  height: 60px;
  border: 1px solid teal;
}
#small-logo {
  height: 60px;
  width: 60px;
  float: left;
  border: 1px solid red;
}
#small-navigation {
  width: 300px;
  height: 20px;
  border: 1px solid black;
  margin: 30px 0 0 10px;
  float: left;
}
#small-search-bar {
  width: 150px;
  height: 20px;
  border: 1px solid aqua;
  float: right;
  margin: 30px 10px 0 0;
}
#content {
  height: 1200px;
  margin-top: 10px;
  border: 1px solid purple;
}

$(function() {
// Stick the #nav to the top of the window
var nav = $('#big-menu');
var navHomeY = nav.offset().top;
var isFixed = false;
var $w = $(window);
$w.scroll(function() {
    var scrollTop = $w.scrollTop();
    var shouldBeFixed = scrollTop > navHomeY;
    if (shouldBeFixed && !isFixed) {
        nav.css({
            position: 'fixed',
            top: 0,
            left: nav.offset().left,
            width: nav.width()
        });
        isFixed = true;
    }
    else if (!shouldBeFixed && isFixed)
    {
        nav.css({
            position: 'static'
        });
        isFixed = false;
    }
});
});        

Answer №1

The following jQuery code demonstrates how to add a specific class to an element when the document is scrolled down by 100 pixels:

var $document = $(document),
$element = $('.fixed-menu'),
className = 'hasScrolled';

$document.scroll(function() {
  if ($document.scrollTop() >= 100) {
    $element.addClass(className);
  } else {
    $element.removeClass(className);
  }
});

You can view this in action on jsFiddle

Answer №2

Instead of completely overhauling the DOM, try utilizing classNames and CSS instead. For example:

<div id="container">
  <div id="menu">
    <div id="logo">Big Logo</div>
    <div id="navigation">Navigation</div>
    <div id="search-bar">Search</div>
  </div>
  <div id="content"></div>
</div>

For the JavaScript part, consider something like this:

$(window).scroll(function() {
  var isCompact = /* true/false; detect scrolling distance */;
  $('#menu').toggleClass('compact', isCompact);
})

This will add or remove the class compact from the #menu element based on a certain scrolling distance. You can then style it with CSS like so:

#logo{height:100px} /* default (big) */
#menu.compact #logo{height:60px} /* small */

These are just examples to get you started. Feel free to customize them to fit your own design needs :)

Moreover, using CSS allows for the possibility of incorporating intricate animations in the future.

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

Executing a javascript function from PHP when a form is submitted: a comprehensive guide

I am looking to trigger a javascript function from PHP when the form is submitted. This function will have access to PHP variables and will use AJAX to send them to a PHP script on another website. The code below serves as an example: <?php .... ..... ...

Is it possible to implement pagination for loading JSON data in chunks in jsGrid?

Currently, I am utilizing jsgrid and facing an issue with loading a JSON file containing 5000 registries into a grid page by page. My goal is to display only 50 registries per page without loading all 5000 at once. Even though I have implemented paging in ...

Is there a specific CSS selector that targets elements with "multiline" content?

My website has a menu that displays with the following CSS: a { background:red; } <a href="#">Home</a> <a href="#">Downloads</a> <a href="#">Contact</a> <a href="#">FAQ</a> <a href="#">Disclaimer&l ...

Utilizing db.system.js Function within the $where Clause

Here is an illustration of a basic function that I have saved: db.system.js.save({_id: "sum", value: function (x, y) { return x + y; }}); However, when attempting to call it within the $where clause, a Reference not exist error occurs. <?php $collec ...

ways of exporting and using arrays in Node.js

Constantly receiving the "undefined" error in main.js: var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); var wordPool = dbaInstance.getWordPool(); console.log (wordPool); The contents of "dbAccess.js" are as follows: var ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

Angular for user authentication page

I've been busy working on the login page, and I've managed to create a login UI that meets the requirements. However, I'm facing some challenges when it comes to validating the username and password. Being new to Angular and Web API, I might ...

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

The Tauri JS API dialog and notification components are failing to function, resulting in a null return value

Currently, I am getting acquainted with the tauri framework by working on a small desktop application. While testing various tauri JS API modules, most of them have been functioning as expected except for the dialog and notification modules. Whenever I tes ...

Is the <ul> tag aligning to the left?

I recently encountered an issue while designing my website. I created a div with a width of 200px on the right side of the webpage, and added a list of links within it. However, I noticed that elements inside the div are aligning slightly to the left, givi ...

What is the process for assigning values once the Google Charts program has completed its drawing?

It might sound strange, but I have a piece of code here: let globalResult = []; let defaultData = ["None", 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200]; $(document).ready(() => { // add a listener to the textbox $('#in ...

chaotic telerik editor arrangement

I have incorporated the Rad Editor into my ASP.NET page. <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <telerik:RadEditor ID="reSummery" runat="server" > </telerik:RadEditor> Despite not referencing ...

Generate a progress indicator upon user clicking a hyperlink

I am looking to implement a loading bar that appears when the user clicks a link. Additionally, I need to upload data (via Ajax) into div#work if needed, followed by displaying the loading bar. Once the data is successfully uploaded, I want the script to s ...

Getting the text from a Selenium element can become tricky when dealing with product discounts that alter the element

(Programming) I am working on selecting random products from a website, some with discounts and some without. For instance: How do I retrieve product 748 (without discount)? or How do I retrieve product 419 (with discount)? When the product ha ...

Is there a way to prevent my table from surpassing the width of my card using CSS?

My table inside a card is not responsive on small screens, causing it to go outside the card. I've tried various solutions like using flex on the parent element and setting the table width equal to the card but nothing seems to work. The card should a ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

Tips for passing a state value to a different state when initializing in react js

I need some help with passing a state value called imagesArray to another state named tabData. It seems like the value is coming up as undefined. Below is the code snippet, can you please point out what I might be doing wrong? constructor(props) { s ...

Filtering a list with Vue.js using an array of checkboxes

Currently, I am exploring ways to filter a v-for list using a checkbox model array with multiple checkboxes selected. Most examples I have come across only demonstrate filtering one checkbox at a time. In the demo here, you can see checkboxes 1-3 and a lis ...