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

A compilation of category listings derived from two arrays of objects that share a common parent ID

I have a challenge with two arrays of objects connected by a parent ID. My goal is to create a categorized list where each category contains the corresponding data set. The structure should consist of a header (category) followed by buttons (data) related ...

Utilizing regular expressions on a URI parameter in JavaScript

I implemented an ajax function that retrieves three images (PORTRAIT, SQUARE, and LANDSCAPE) from a JSON response: $.ajax({ url: link, method: 'GET', headers: { "Authorization": authToken ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...

development of MapLayers with rails and javascript

As a newcomer to RoR, I am encountering an issue that seems to be eluding me. I attempted to replicate the example application found on the mapLayers GitHub repository at https://github.com/pka/map_layers/wiki. However, all I see is the JavaScript code gen ...

My Tailwind CSS toggle button disappears in dark mode, why is that happening?

<button aria-label="Toggle Dark Mode" type="button" className="lg:inline-flex lg:w-40 md:w-screen p-3 h-12 w-12 order-2 md:order-3" onClick={() => setTheme(theme === 'dark' ? &ap ...

What is the best method for testing different versions of the same module simultaneously?

My goal is to distribute a module across various component manager systems like npmjs and bower. I also want to provide downloadable builds in different styles such as AMD for requirejs, commonJS, and a global namespace version for browsers - all minified. ...

Is there a way to convert a JavaScript object to a class while eliminating unnecessary properties?

In my current project, I am using Typescript with ExpressJS to build APIs. Let's say I have a typescript User model defined as follows: class UserModel { id: number; email: string; password: string; name: string; dob: Date; ge ...

Refresh the PHP MySQL table view based on selection changes in the dropdown menu

Hello there! I currently have a table displayed on my page thanks to the following code: $result = mysql_query("Select * from porders, porders_detail, parts where porders.order_no = porders_detail.order_no and porders_detail.om_part_no = parts.om_part_no" ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

Having difficulty setting responseText after making a jQuery ajax request

I've been developing a test giver app which has been working smoothly with the allQuestions JSON object embedded in the code. Now, I'm looking to relocate the allQuestions object from the index file to a separate file called test.json and retriev ...

Detecting unutilized space in a collection of divs with varying sizes using JavaScript and CSS

To better understand my issue, I created a StackBlitz demo: https://stackblitz.com/edit/angular-aqmahw?file=src/app/tiles-example.css Screenshot My tiles can have four different widths (25%, 50%, 75%, 100%). The tiles must fit on only two lines, so if a ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

The tooltip in chart.js stubbornly holds onto past data even after it's been

Utilizing chart.js, I have implemented a feature where a tooltip displays when a user hovers over the chart successfully. However, I encountered an issue. I added an option for users to un-check data-points, which works correctly. But now, the tooltip fun ...

Stack 2 cards inside a DIV vertically using Materialize CSS

My form and table are currently positioned side by side in 2 columns: The layout of this form/table is built using datatable + materialize CSS. I am looking to place the Form and table within a div to ensure that the bottom of both elements are always al ...

Stop the event propagation when the back button is clicked

While utilizing ons-navigator, I am looking to customize the function of a particular element at a certain stage. Employing the onClick handler has allowed me to successfully trigger this function. However, upon exiting the onClick handler, the navigator ...

The specified package, [email protected], fails to meet the peerDependencies criteria set by its sibling modules

Encountering errors when attempting to run npm install. I'm puzzled why it's not working despite using the most recent version of React. npm ERR! peerinvalid The package <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

Create another div for the remaining vertical space occupied by the sibling div?

I currently have 3 different divs nested within each other: <div class="a"> <div class="b"> </div> <div class="c"> </div> </div> Here is the current CSS styling applied to these divs: .a { hei ...

Wrapping dynamic page titles with comment tags in NextJS for cleaner code

I am currently working on NextJS version 12. In my project, I have a file named Layout.js which contains the following code: import Head from "next/head"; const Layout = ({children, pageTitle, mainClass}) => { return ( <> ...

The scrolling feature within individual div elements seems to be malfunctioning in Ionic 2

In my current project using Ionic 2, I am faced with the task of designing a screen that contains two distinct grid views. The first grid view needs to occupy 40% of the height, allowing for scrolling within that specified area. On the other hand, the se ...

Incorporating external CSS stylesheets into a custom LESS framework

Is there a reliable method for integrating a third-party CSS file obtained from an external source into my own LESS compile structure without making many changes to it? I anticipate that the external CSS file may be updated periodically, so I would prefer ...