Assigning a class to a header upon loading the page from various sections at random

After scrolling, I used JavaScript to add a class to <header>. Here is the code snippet:

 $(window).scroll(function(){

    var top = $(window).scrollTop();
    if(top>=1){
        $("header").addClass('bg-header');
    }

    else
        if($("header").hasClass('bg-header')){
            $("header").removeClass('bg-header');
        }
});

However, there seems to be an issue. When reloading the page from a section other than the very top (e.g. footer), the header loses the added class and only regains it after scrolling down. How can I ensure that the added class remains even after a reload?

Answer №1

There are a couple of different ways to approach this issue. One method is to manually trigger the scroll event either on page load or when the DOM is ready. Another option is to consolidate all of the logic into a function that can be called by the scroll event as well as during page load or when the DOM is ready.

Solution 1: Utilize a custom function for scrolling and page events

$(function() {

    // Create custom function to handle all necessary logic
    var customScrollCallback = function() {
        var top = $(window).scrollTop();
        if (top >= 1) {
            $("header").addClass('bg-header');
        } else if ($("header").hasClass('bg-header')) {
            $
        };
    };

    $(window).scroll(function() {
        // Call custom function on scroll
        customScrollCallback();
    });

    // Execute custom function at runtime :) (a handy trick!)
    customScrollCallback();
});

Solution 2: Manually trigger the scroll event (not recommended)

This second solution may not be ideal because there could be other plugins or scripts on the page that rely on the scroll event. When you manually trigger this event, it disrupts the expected behavior of the event (as it fires without any actual scrolling occurring).

$(function() {
    $(window)
    .scroll(function() {

        var top = $(window).scrollTop();
        if (top >= 1) {
            $("header").addClass('bg-header');
        } else if ($("header").hasClass('bg-header')) {
            $("header").removeClass('bg-header');
        }
    })
    .trigger('scroll');
});

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

Can jQuery be used to target pseudo elements such as scrollbars for selection?

Can you use jQuery to target pseudo elements like these: ::-webkit-scrollbar ::-webkit-scrollbar-track ::-webkit-scrollbar-thumb Is it possible to manipulate them through jQuery? #scroller { background: #fff; height: 300px; wid ...

Struggling with expanding a Javascript object? Let us assist you!

Imagine having a JavaScript object... app.widget = {} (function (W) { W.superFunction = function() { console.log("Hey!"); } ...other functions... })(app.widget) Now, let's create a clone of this object... app.specialWidget ...

Enhance your HTML audio player with added timeline functionality

I'm currently working on incorporating an HTML audio player into my project. I've managed to get the play/pause functionality to work, but now I'm stuck on adding a timeline feature. Additionally, I'm not sure how to implement the play/ ...

switch between showing and hiding dynamic table rows

As I dynamically add rows to a table, each row can either be a parent row or a child row. My goal is to toggle the visibility of child rows when the parent row is clicked. if (response != null && response != "") { ...

Using a function as a prop in Vue js to retrieve data from an API

I am facing an issue with a component that I want to decouple from the data fetching implementation. My goal is to be able to pass a data fetching callback as a prop. The reason for this is so that I can easily mock the data fetching process in storybook. ...

Teaching you how to incorporate empty spaces and punctuation within JOI

How can I modify Joi to permit spaces/whitespaces in a title field within a form? Scheduled to work with Jude tomorrow. I want to allow entries like: Morningwalk Currently, only the second example is passing validation. Below is my existing Joi val ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

Alert Box Displays Variable Name Instead of Label Name in Form Validation - MM_validateForm()

Looking at the screenshot, you can see variable names such as "email_address", "email_message" and "email_subject". I would like these to be displayed as "Email", "Message" and "Subject" instead. The validation in this form is done using MM_validateForm() ...

Generate a fresh object with distinct identifiers

I am interested in creating a new object, utilizing unique keys consisting of comma-separated IDs. For instance, I have: const d = { "1,2,3,4,5,6,7,8,9,10": [ "created_by", "modified_on", "external_o ...

Adjust the color of the text in the Stepper component using React Material UI

Is there a way to modify the text color within the stepper? Specifically, I aim to have the number 3 displayed in black instead of white: Image Link ...

Ways to bring in external javascript files in reactjs

I'm currently working on a form that requires the user to input their location. To achieve this, I have integrated the npm package react-geosuggest-plus. However, I want to avoid including <script src="https://maps.googleapis.com/maps/api/js?key=AI ...

Creating a seamless integration of images and backgrounds using CSS

Can you help me find a way to blend the image with the background to eliminate the visible separation between them? Here is the link to the image: https://i.stack.imgur.com/VB9in.jpg ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

Ways to halt a script entirely once its tag has been eliminated

I have a script from a page tracker website that runs periodically. Occasionally I need to restart the script from the beginning. To do this, I typically remove the script tag from the DOM and then re-append it. However, because the script utilizes setInt ...

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

Conceal a form depending on the referer_url parameter

I am looking to customize my 404 page by displaying a small form only when the visitor comes from a website, not from an email link or directly entering the URL. The purpose of this form is to address broken links that led the visitor to the error page. If ...

"Utilizing multiple optional parameters in Expressjs can lead to the request handler being

Hey there, I could use a fresh perspective on this issue I'm having. I am attempting to set up a request handler that can accept 0, 1, or 2 parameters like http://localhost:3000/{seed}/{size}. The parameters "seed" and "size" should both be optional. ...

Ensure that the heights of columns in UL CSS are aligned regardless of the number of lines they contain

In my current project, I am using CSS columns to establish a two-column layout for an unordered list. Here is the code snippet: HTML <div class="meta-data"> <ul> <li><i class="fa fa-chevron-right fa-xs"></i><str ...

What sets apart the <img> and <Image> layout attributes in NextJS?

While working on custom checkboxes, I came across a unique situation - the only way the positioning of the checkboxes aligns properly is if the classes '.init' and '.hover' are assigned to images, and the class '.done' is disp ...