Assign a CSS class when the page is loaded

I have the following HTML code:

<body class="page-header-fixed page-sidebar-closed-hide-logo page-content-white page-sidebar-closed" style="background-color: #F5F5F5">

When the page loads, the sidebar closed CSS will be applied.

Currently, I am using jQuery and HTML storage to save and retrieve the toggle value of the navigation bar.

var sidebar = $('.page-sidebar');
var sidebarMenu = $('.page-sidebar-menu');
var body = $('body');

if (localStorage.getItem("toggler") == 'close')
{
  body.addClass("page-sidebar-closed");
  sidebarMenu.addClass("page-sidebar-menu-closed");
}
else
{
  body.removeClass("page-sidebar-closed");
  sidebarMenu.removeClass("page-sidebar-menu-closed");
}

My issue is that when the page loads, it always loads with a closed sidebar. This isn't a problem if the user has clicked "Closed" and that choice is stored in local storage - the page then loads correctly with the sidebar closed.

However, if the user has clicked "Open", the page first loads with a closed sidebar because it is given the class 'page-sidebar-closed'. Then, the jQuery function opens it, resulting in a flicker of the sidebar whenever the page loads - toggling between closed and open.

Is there a way to directly apply a function on a class?

Answer №1

If you want to execute certain actions once the document is ready, you can utilize

$( document ).ready(function() { }
. This allows you to modify the class of your sidebar based on the user's last action. It's essential to ensure that your JavaScript files are loaded before your CSS files to prevent any flickering effect, even though it may result in increased load time.

The following example demonstrates changing the color of a div when the page is ready:

$( document ).ready(function() {
    // change div color to blue on page ready
    $("#demo").removeClass('red-box').addClass('blue-box');
});
.red-box{
  width: 50px;
  height: 50px;
  background-color: #F44336;
}

.blue-box{
  width: 50px;
  height: 50px;
  background-color: #2196F3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo" class="red-box"></div> <!-- div with red color -->

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

What are some other options for pushing out data instead of using window.onbeforeunload?

I have an AJAX function that interacts with my PHP script. The purpose was to delete empty MySQL entries when the user closes the page. Initially, I thought window.onbeforeunload would be ideal for this task, but it seems in the latest version of Chrome i ...

The wasm URL file scheme cannot be loaded as it is not supported

Currently, I am exploring the functionality of sql.js through this resource: My journey began with their introductory HTML example which seems to be causing a series of errors during execution. To start off, I installed sql.js using the command: npm inst ...

Can I use my local network/browser to download an html file from a webpage as if I manually downloaded it using javascript or nodejs?

As someone who is relatively new to javascript/nodejs and its packages, I have a question about downloading files. Is it feasible for me to download a file using my own local browser or network? Typically, when researching how to scrape or download html ...

Having trouble getting my Jquery Ajax post request to work with JSON data

I am working on syncing data from my Phonegap app back to the server. I have a PHP script set up on the server to handle the incoming data and now I need to figure out how to post values from my App to this script. Currently, I store my data in a SQLite d ...

Trouble with the onload function in onMounted vue3

For my vue3 component, I need to load certain scripts. Here is what I am currently implementing: <script setup> import { onMounted } from 'vue' function createElement (el, url, type) { const script = document.createElement(el) if (type ...

Understanding and resolving asynchronous issues in jQuery success callback functions

When utilizing Ajax to retrieve XML and processing it by invoking a function upon success, everything runs smoothly. From the success function (handleHousestark), the XML is examined and another function (getJonSnow) is called to include additional data. T ...

Tips for concealing the loader once all pages have been loaded

Within the context of my website development project at , I am utilizing a script for infinite scrolling to consolidate multiple pages into one seamless scrolling experience. I am seeking a solution to hide the loader (the spinning icon) when no additiona ...

Connecting NGINX to a Node.js cluster with proxy_pass

After setting up both a NGINX server and a node.js process, the node.js code structure is as follows: function initiateCluster() { var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i ...

Can global scope be injected into a class instantiated in ES6, also known as a singleton?

Before I get started, I want to apologize in advance for the lengthy code that is about to follow. It may make this question seem a bit bloated, but I believe it's necessary for understanding my issue. Imagine we have a predefined MainModule: ' ...

Preventing the need to reset JavaScript text inputs

I'm encountering a strange issue in my code. I'm developing a graphing calculator that requires users to enter multiple expressions for evaluation. I have a text input and a button that adds a new input to the parent div whenever it is clicked: d ...

Issue with submitting form in React when state changes upon button click event

I have created a button group to filter the table. The button group changes the color of the active button when clicked. To allow for multiple button groups for filtering, I decided to wrap the table and button group in a form element. However, when I clic ...

Leverage JavaScript to customize the appearance of existing links within an external HTML document

Forgive me for my lack of expertise in Javascript. I will do my best to explain clearly. On my website, I have an external html file for the navigation menu that is loaded with javascript to simplify editing (so I don't need to update nav elements on ...

AngularJS is experiencing delays when processing subsequent $http delete requests, leaving them stuck in a

I am currently working on a project where I have a table displaying a list of objects, with each object having multiple child objects associated with it. The technologies I am using include Angular 1.2.20, Express 4.6.1, and Node 0.10.25. In the table, the ...

The accumulation of MVC 3 Ajax requests is becoming overwhelming

I'm currently working on the following code snippet: $('.defaultLink').click(function () { $.ajaxSetup({ cache: false }); cleardiv(); $('#mainContent').empty() $('#mainContent').load(this. ...

Align the items in the center of a Bootstrap navigation bar

I am looking to center the navigation menu items on my navbar. Currently, my navbar layout appears like this: https://i.sstatic.net/BqRwW.png Specifically, I want "Users", "Admin", and "Records" to be centered within the navbar. Additionally, I would lik ...

Creating a function in Angular to locate each object based on its ID

Hello there, I am currently working on creating a method called findChildByIdInData(data:any, childId:string). This method will take in a JSON main node with children that have unique IDs, and the goal is to find a specific object based on the ID provided ...

Has Next.js incorporated a maximum cache size feature along with an invalidation algorithm like LRU?

Currently, I have a Next.js site that utilizes getServerSideProps for data fetching. However, I am interested in switching to getStaticProps and implementing incremental static regeneration (ISR) for improved performance. Currently, my memory usage is ap ...

The CSS gradient background fails to fully cover the background when scrolling on the web browser

My webpage has a beautiful gradient background, but unfortunately, when the page is zoomed in, the gradient stops working and only the background color is displayed. Here is a snippet of the code: <html> <head> <style type="tex ...

Can a prototype be created in JavaScript for a "FileList" object type that enables the construction and addition of a "File" object within it?

This is my first time attempting to create a prototype, and I'm struggling to grasp the concept of callback functions. My current project involves automating the firmware update process for our company's routers using Python, Selenium, and Phant ...

How to make sure a function in jQuery only runs once

When mySepsisTimer, a simple countdown timer, is initiated once certain selection criteria (sepsis-six-sirs) are met, an issue arises if a user clicks on another option select after the timer has started, causing a duplicate clock to run. How can I ensur ...