Ways to display and conceal menu depending on initial view and scrolling

On my website, I have implemented two menus - one to be displayed when the page loads and another to show up when a scroll occurs. You can view my page here.

The goal is to have the white part visible when the position is at the top, and switch to the blue part upon scrolling past the top position.

Here is the current code snippet that I am using:


<script type="text/javascript" src="//code.jquery.com/jquery-git.js"></script>
<script type='text/javascript'>
    $(function(){
        var didScroll;
        var lastScrollTop = 0;
        var delta = 5;
        var navbarHeight = $('header').outerHeight();

        $(window).scroll(function(event){
            didScroll = true;
        });

        setInterval(function() {
            if (didScroll) {
                hasScrolled();
                didScroll = false;
            }
        }, 250);

        function hasScrolled() {
            var st = $(this).scrollTop();

            if(Math.abs(lastScrollTop - st) <= delta)
                return;

            if (st > lastScrollTop && st > navbarHeight){
                $('header').removeClass('nav-bar-below op-page-header cf').addClass('banner include-nav');
            } else {
                if(st + $(window).height() < $(document).height()) {
                    $('header').removeClass('banner include-nav').addClass('nav-bar-below op-page-header cf');
                }
            }

            lastScrollTop = st;
        }
    });
</script>

I'm facing issues with this implementation. Can someone please assist me in resolving this problem?

Answer №1

To determine if the scroll is at the top of the page or not when the scroll event is triggered, you can display a white header if it is at the top and a blue header if it is not.

$(window).scroll( function() {
    var scrollPosition = $(window).scrollTop();

    if(scrollPosition === 0) {
        //show white header
    }
    else {
       //show blue header
   }
}

Ensure that when the page initially loads, the white header is displayed first using CSS since the code above will only run when the user scrolls (triggers this event).

*EDIT

Regarding displaying the blue header when there is a scroll past the top position, you can try using this plugin:

Answer №2

Here is an example code snippet to help you fix the menu at the top of the page.

$(document).scroll(function() {

var y = $(document).scrollTop()
var header = $('.include-nav');
var blueMenu = $('.cf');
var screenHeight = header.height();
if (y >= screenHeight) {
    blueMenu.css({
        position : "fixed",
        "top" : "0",
        "left" : "0"
    });
    header.css("position", "relative");
} else {
    blueMenu.css("position", "relative");
}
});

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

Mastering the art of calculating the width for a responsive scroll menu

I found a useful tutorial on building a scrolling menu for smaller screen sizes. You can check it out here. However, I encountered an issue when trying to add a border width element. Whenever I define the width, it overrides the scrolling: auto; element. ...

What is the best way to increase the spacing between inline-block elements?

Just to clarify, I am not looking to delete space between inline-block elements - rather, I want to insert it. My goal is to create a grid of menu items that can accommodate 2, 3, or 4 items per row, and I hope to achieve this using media queries. Is the ...

Transferring data from a stream in NodeJS to FrontEnd using ReactJS

How are you doing? I'm trying to figure out how to send a large data request from PostgreSQL to the FrontEnd in JSON format. Can anyone help with an example of how this can be achieved? Thank you. Here is my code: const express = require('expr ...

The absence of req.body in the app reflects an undefined state

I'm encountering an issue with my app and I believe showing you my code is the best way to explain the problem: var Meetup = require('./models/meetup'); module.exports.create = function (req, res) { var meetup = new Meetup(req.body); c ...

Angular's table data display feature is unfortunately lacking

Below is a simple HTML code snippet: <div class="dialogs"> <div id="wrapper" > <p>{{createTestingConstant()}}</p> <ng-container *ngFor="let one of contacts"> <p>{{one ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

What steps should be followed to execute this moment.js code in an Angular.js controller using Node.js?

I am trying to adapt the following node.js code that uses moment.js into an AngularJS controller: var myDate = new Date("2008-01-01"); myDate.setMonth(myDate.getMonth() + 13); var answer = moment(myDate).format('YYYY-MM-DD'); To achieve this, I ...

Direct users according to their browser language (excluding php)

My site is going to have content in 3 languages, with French set as the default (fr). Here's how the structure of the website looks: Root directory (important note: no php files, just plain html) /fr/ Index.html About-us.html Contact.htm ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

What exactly entails static site generation?

I have been exploring the concept of static site generation (SSG). The interesting question that arises is how SSG can fetch data at build time. In my latest application, I implemented an event handler to retrieve data based on a user's search keyword ...

Navigating to lower levels of JSON data in JavaScript instead of starting with the top level

Using a microservice, I fetch multiple sets of JSON data and display them on a Vue.js-powered page. The structure of the data is as follows: {"data":{"getcompanies": [ {"id":6,"name":"Arena","addr ...

Switching input types in Android WebView: From Numeric to Password

I am facing an issue with my webview. In the webview, I have three input types: Number Text Password The problem is that when I switch from the number input field to the password input field, the numeric keyboard opens up instead of the qwerty keyboard. ...

Ways to designate a parent element in Vue Draggable when the element is lacking a child

I'm currently incorporating vue-draggable into my project from the following GitHub repository: https://github.com/SortableJS/Vue.Draggable Below is my ElementsList component: <div> <draggable v-model="newElement" :move ...

Can someone guide me on how to locate and access the port number?

In my Reactjs project root directory, I've created a .env file. This is what's inside my .env file: PORT = 30001 ... In my App.tsx file, I'm trying to access the port like this: const PORT_NUMBER = process.env.PORT; When I run yarn start ...

Object oriented caching in jQuery

HTML: <div class="navigation"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </d ...

Looking for a versatile jQuery plugin that enables right-click functionality across different browsers?

I am currently using a context menu plugin that displays a context menu when an element is right-clicked. However, this does not work on elements embedded with ajax. To solve this issue, I am considering utilizing ajax live to trigger the context menu func ...

A highly effective method for nesting items within a list through recursive functions

I am currently in the process of developing my own commenting system because I have found that existing platforms like Disqus do not meet my specific needs. My backend is built using NodeJS and MongoDB, and I need to execute two primary queries on my data ...

Guide to dynamically setting the title and background color of the navigation bar in React Navigation 5

In my current project, I am utilizing React Navigation Bar version 5 and have successfully set the title in App.js. However, I now need to change this title dynamically when the screen is rendered. I attempted to use this.props.navigation.navigate('Ex ...

Leveraging the power of AJAX to submit forms on a webpage that are dynamically created by PHP

On my page, there are multiple forms that serve as a "like" button for each post. Next to these buttons is a div called "likes$id" where the number of likes is displayed. This allows me to easily update the like count after making an AJAX call. However, I ...