Improving Performance in JavaScript by Altering Class Properties

I need to dynamically change the color properties of two classes, but my current code is sluggish since these classes are repeated over 100 times throughout the code.

Any tips on optimizing this for better performance?

if (mainColor) {
    var elColors = document.querySelectorAll('.color')
    elColors.forEach(el => el.style.color = mainColor)
    var elBgColors = document.querySelectorAll('.bg-color')
    elBgColors.forEach(el => el.style.backgroundColor = mainColor)
}

(the user input provides the mainColor)

Answer №1

To maximize performance, it's best not to individually set styles for each element.

Instead, assign a new class to the parent element.

For instance:

In a dynamic manner - Using JavaScript:

var styles = document.querySelector('head style#dynamic'),
    sheet;

if (!styles) {
    styles = document.createElement('style');
    styles.id = 'dynamic';
    document.querySelector('head').appendChild(styles);
}

sheet = styles.sheet;
sheet.insertRule("body.mainTheme .color { color: red; }", 0);
sheet.insertRule("body.mainTheme .bg-color { background-color: blue }", 0);

if (!document.body.className.match(/(^|\s)mainTheme(\s|$)/s)) {
    document.body.className = document.body.className + " mainTheme";
}

In a static manner - JavaScript Section:

// jQuery: $('body').addClass('mainTheme');
if (!document.body.className.match(/(^|\s)mainTheme(\s|$)/s)) {
    document.body.className = document.body.className + " mainTheme";
}

In a static manner - CSS Section:

.mainTheme .color {
    color: red;
}
.mainTheme .bg-color {
    background-color: blue
}

Answer №2

Although you've already approved a satisfactory answer, it's beneficial to introduce another alternative that makes use of CSS custom properties. This method involves updating a custom property (referred to as a 'CSS variable') in one central location so that the change is reflected wherever that custom property is utilized:

function updateColors(mainColor) {
  if (mainColor) {
    let root = document.querySelector(':root');

    root.style.setProperty('--customColor', mainColor);
  }
}

document.querySelector('input[type=color]').addEventListener('input', function(){
  updateColors(this.value);
});
:root {
  --customColor: red;
}

body {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
}

div.color {
  color: var(--customColor);
}

div.bg-color {
  background-color: var(--customColor);
}
<label><input type="color" /></label>
<div>no class</div>
<div class="color">'color'</div>
... (remaining code snippets omitted for brevity) ... 

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

intl-tel-input's getExtension function is returning a value of 'null'

I've been attempting to retrieve the extension of the mobile number that has been input. All other variables are functioning correctly, but the extension variable is returning a null value. It appears that it is sending a null value to the POST method ...

Changing the way in which text is selected and copied from a webpage with visible white space modifications

After working on developing an HTML parser and formatter, I have implemented a new feature that allows whitespace to be rendered visible by replacing spaces with middle dot (·) characters and adding arrows for tabs and newlines. https://i.sstatic.net/qW8 ...

Retrieve data from a REST API in a dynamic manner without manually specifying the table structure in the HTML code

I am looking to retrieve JSON data via a post request from a REST API: http://localhost/post1 param1='1' The response will look like this: { "json_table": [ { "date": 123, "test": "hello2" }, { "date": 19, ...

Implement JQuery to include a screensaver on your website

My website in asp.net c# displays the performance of a specific process on an LCD TV screen. The data is refreshed every 15 seconds using the code below: <div id="InfoTop"> <table width="100%" cellpadding="0" cellspacing="0"> ...

Encountering MIME type error (text/html) during Angular project deployment

I am facing an issue while trying to deploy a project built with Angular/CLI 6.12.0. After transferring the content of the "dist" folder to a server, I encountered a console error related to MIME type. The module at address "http://www.sylvainallain.fr/p ...

What is the reason behind utilizing arrow functions in React event handlers?

function ButtonIncrement(){ const [count,setCount] = useState(0); render(){ <div> <h3> <button onClick={() => setCount(count+1)}>Increase count for amusement</button> <p>Total C ...

Connect an Angular Service object to a Controller's Scope and keeping it in sync

I am facing an issue with the interaction between my EmployeeService and EmployeeController. The service contains a specific object which I bind to the controller's scope: app.controller('EmployeeController', function($scope, EmployeeServic ...

Divide the array based on its individual values

I am dealing with an array like the one below: var aaa = [ [[value1,value2],[0,0]], [[value3,value4],[0,1]], [[value5,value6],[1,0]], [[value7,value8],[0,2]], [[value9,value10],[1,1]], [[value11,value12],[2,0]] ]; Now, I want to split this ar ...

Executing a windows application on the client side from aspx.cs

I have created a windows application in C# that is installed for clients. I now need to run this windows application from the client's side when a user clicks a button on an ASP.NET web application. Explanation My task involves scanning hard copies ...

Looking to extract the first URL from a string using JavaScript (Node.js)?

Can someone help me figure out how to extract the first URL from a string in Node.js? " <p> You left when I believed you would stay. You left my side when i needed you the most</p>**<img src="https://cloud-image.domain-name.com/st ...

Creating a bottom bar using React and Material UI

I'm currently working on implementing a footer that will be displayed on every page of my Next.js application. To style this, I am utilizing Material UI. The following component is responsible for defining the layout across all pages of the app: impo ...

preventing a nested JavaScript function from being executed multiple times

Trying to implement a JavaScript function to run only once has proven to be quite a challenge for me. Despite exploring previously asked questions like Function in javascript that can be called only once, none of the suggested solutions seem to work for me ...

The AJAX functionality is not triggering the necessary C# controller method

I have been facing a challenge with my AJAX implementation as I am still new to using it. The problem arises when trying to reach the C# method it should call - even after setting a breakpoint, the code is never reached and no errors are displayed. While ...

Typescript error: The argument containing 'username' and 'password' fields cannot be assigned to a parameter expecting only a 'string' type

My service is designed to take an endpoint and execute a HTTP call. Here is the code snippet: export const updatePassword = (data: { username: string; password: string; }): HttpResponse<string> => { const { usernam ...

JQuery kicks off the function when the document is loaded and also when the window

I am currently working on implementing a menu that slides in and out from the left side when an icon is clicked. Everything works smoothly, but I need the menu to behave differently based on the browser size. To achieve this, I must determine the browser ...

I'm looking for a more efficient and graceful way to implement jquery .slideToggle on numerous hidden divs. Any suggestions?

If you would like to see a demonstration of what I am working on, here is a link to a live example: https://jsfiddle.net/yfe7ky3x/ My goal is to create a basic portfolio website that showcases various projects. I want to implement a feature where clicking ...

"Implementing a Texture as Material in Three.js: Step-by-Step Guide

I recently discovered Three.js and I'm really enjoying it. As a newcomer to JavaScript, I'm eager to delve deeper into animation and related topics. //UPDATE I've been working on this code snippet, but unfortunately, it's not functioni ...

Error encountered while sending AJAX request with JSON data type

Is it possible to submit a Form using ajax with the jsontype? Suppose I have 5 fields in the form, where 4 of them are normal textboxes and one field contains JSON. When trying to send this data via ajax, an error is thrown. How can I resolve this issue? ...

Redux: The action was effectively triggered, but the state remained unformed

I'm currently working on a project to familiarize myself with Redux. I am using the Redux DevTools to monitor my two states: lists and todos. However, I am running into an issue where only todos are being displayed, despite trying various troubleshoot ...

Toggle visibility of div elements in a list

Users have the option to either download a file by clicking on "download" or view it as a PNG in their browser by clicking "open". I found a solution on this platform for creating a show/hide toggle function. It worked well for one item, but I'm look ...