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

Enhancing jQuery OrgChart with personalized AJAX request headers

Is there a way to set request headers on an ajax call using the OrgChart library? I attempted the following: $('#chart-container').orgchart({ 'data' : '/api/v1/profiles/orgchart/', 'beforeSend&ap ...

Rendering components asynchronously in ReactJS

After completing my ajax request, I need to render my component. Here is a snippet of the code: var CategoriesSetup = React.createClass({ render: function(){ var rows = []; $.get('http://foobar.io/api/v1/listings/categories/&apo ...

Chrome and Safari browsers are both experiencing a glitch where the Full Calendar event time is automatically adding an

Currently, I am utilizing Jquery fullcalendar 3.3.1 and moment.js 2.15.1 to display an event calendar. When clicking on an event, a modal popup showing the event details appears. The event details are stored in an SQL database, and ajax is used to populate ...

What causes the off-canvas menu to displace my fixed div when it is opened?

Using the Pushy off-canvas menu from GitHub for my website has been great, but it's causing some trouble with my fixed header. When I scroll down the page, the header sticks perfectly to the top, but once I open the off-canvas menu, the header disappe ...

Injecting Dependencies Into ExpressJS Routes Middleware

Hey there! I'm currently working on injecting some dependencies into an expressjs route middleware. Usually, in your main application, you would typically do something like this: const express = require('express'); const userRouter = requi ...

What is the most effective method for refreshing a control following an Ajax request?

I am currently working on a website that sends an Ajax request to save data to a database. I would like to update the webpage to show the user that their changes have been successfully submitted. I have brainstormed three possible solutions: Immediately ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Tips on making a material-ui grid fill up the entire screen

Currently, I am working on developing a layout that resembles most editor/IDE setups using material-ui and react. In this layout, I have a top bar, a bottom bar, side panels on both sides, and a center area. My main concern is how to ensure that this grid ...

Implementing scrolling functionality within a nested container

I need help with getting a nested container (.widget2) to scroll while still keeping the borders intact. Currently, the inner container is scrolling past the bottom edge of the parent container, and the scrollbar isn't displaying correctly. If you w ...

What are some ways to optimize Ajax requests for improved speed when multiple identical requests are made on a single webpage?

When the webpage is loaded, a block is dynamically created using an Ajax call to retrieve data from another page. This structure is then populated and added to a specific DOM element. However, multiple Ajax calls during page loads are causing delays. Is ...

Firefox is having trouble loading SVG files

For some reason, the SVG image is loading on all browsers except for Firefox. I checked the DOM but couldn't find the code. Just to clarify, I am serving the page from Tomcat 9.0.34 <kendo-grid grid-options="gridOptions"> <img src= ...

When setting the request header in XMLHttpRequest, the $_POST variable will be null

I encountered an issue while trying to send a request using XMLHttpRequest in JavaScript code with PHP. Whenever I set the request header using `setRequestHeader`, the `$_POST` value returns null. However, if I remove `setRequestHeader`, the `$_POST` data ...

What is the best way to adjust the dimensions of an element so that it only fills the size of the initial window or

I need help keeping a specific element at the initial 100% height of the viewport, without it resizing when the user changes their window size. Should I use JavaScript to determine the initial viewport height and then pass those dimensions to the CSS? Can ...

Creating a custom date selection component in Angular 2 RC1

Can anyone recommend a datepicker that is compatible with Angular 2 RC1? I noticed that ng2-datepicker seems to be using angular2 RC1, but when trying to install it, it's asking for Angular 2 Beta. Would appreciate any assistance. Thank you in advan ...

AngularJS: dynamic autocomplete field with scroll functionality

This is my HTML code: <div class="form-group"> <label class='control-label col-md-4' for='id_paymentCurrency'>{{'PAYMENT_CURRENCY' | translate}}</label> <div class='col-md-4'> ...

Encountering syntax errors in GraphQL

Currently, I am in the process of working on the GraphQL Node tutorial and have reached step 7. Visit this link to view Step 7 While implementing the code in my datamodel.prisma file, I encountered several syntax errors: directive @id on FIELD_DEFINITIO ...

Creating a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

What is the best approach to send data to the parent when closing $mdDialog?

When I open a Dialog Window, it has its own controller. Is there a way for me to modify data in the differentController that belongs to the Dialog Window and then send the modified data back to the parent controller when the dialog is being removed? fun ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

What separates $(document).ready() from embedding a script at the end of the body tag?

Can you explain the distinction between running a JavaScript function during jQuery's $(document).ready() and embedding it in the HTML within script tags at the bottom of the body? Appreciate your insights, DLiKS ...