Is it possible to change the color of multiple elements at once using Javascript?

Hi there! I've been working on this code that allows me to change the color of the sidebar on an HTML page using a color picker and saves it to local storage.

But now, I'm having trouble figuring out how to use the same code to change the color of other elements, such as buttons, with the color picker. Currently, only the sidebar changes color.

You can check out my current situation here: https://codepen.io/anon/pen/wyVQbe

/*Set your own color*/
var jscolor;
var defaultColor = (localStorage.getItem("color")) ? localStorage.getItem("color"): "#0078c0";

window.addEventListener("load", startup, false);
function startup() {
  jscolor = document.querySelector(".jscolor");
  if (jscolor) {
    jscolor.value = defaultColor;
    jscolor.addEventListener("input", updateFirst, false);
    jscolor.addEventListener("change", updateAll, false);
    jscolor.select();
  }
  refreshSidebar(defaultColor);
}

function updateFirst(event) {
  refreshSidebar(event.target.value);
}

function refreshSidebar(color) {
  var side = document.querySelector(".sidebar");
  if (side) {
    side.style.backgroundColor = color;
  }
}

function updateAll(event) {
  document.querySelectorAll(".sidebar").forEach(function(side) {
    side.style.backgroundColor = event.target.value
    localStorage.setItem('color', event.target.value);
  });
}

Answer №1

An approach (which may or may not be ideal)

You can differentiate all elements as shown below.

<div class='themecolor onlyTextColor'> hello1</div>
<div class='themecolor'> hello2</div>
<div class='themecolor onlyTextColor'> hello3</div>
<div class='themecolor'> hello4</div>
<div class='themecolor'> hello5</div>

Elements with the class onlyTextColor should only update the text color, while the others should update the background (You can also have another class like onlyBackground to update only the background)

and implement something similar to the code below (since you mentioned using jQuery)

 $('.themecolor').each(function(){
     localStorage.setItem('color', rgba);
    if ($(this).hasClass("onlyTextColor"))
      {
          $(this).css('color', rgba);
      }
    else
      $(this).css('background-color', rgba);
  }) 
}

Check out this demo on Codepen

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

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

What is the process for making a button that only consists of text?

Is there a way to design a button that displays text like a hyperlink, but still maintains the <button> characteristics? ...

How can one utilize electron's webContents.print() method to print an HTML or text file?

Electron Version : 2.0.7 Operating System : Ubuntu 16.04 Node Version : 8.11.1 electron.js let win = new BrowserWindow({width: 302, height: 793,show:false}); win.once('ready-to-show', () => win.hide()); fs.writeFile(path.join(__dirname ...

Executing an AngularJS function within a form element using the ng-submit directive

I have created an AngularJS function that I intend to call in my form tag. However, when I use this function in my html form within the ng-submit attribute, it does not redirect or perform any action. When I click on the button, nothing seems to happen a ...

Is it possible to connect to a Node server from outside the network if the application is only listening on 'localhost'?

When utilizing the Express framework and we implement app.listen(port), the app will be located at localhost:port/ On a local machine, it is clear how to access this address using a local browser running on the same machine. Even clients within the same n ...

Troubleshooting the Google OAuth 2.0 SAMEORIGIN Issue

Trying to bypass the SAMEORIGIN error while using Google's JavaScript API is a timeless challenge. Here is an example of what I have tried: let clientId = 'CLIENT_ID'; let apiKey = 'API_KEY'; let scopes = 'https://www.google ...

HTML - maximizing the potential of 'learn more' option

Is there a way to seamlessly display the rest of a blog post without redirecting to another page in HTML? I'm looking for a "continue reading" link that, when clicked, will expand the remaining content underneath the current text without reloading the ...

iPhone experiencing no response to HTTPS AJAX request

$(function () { var apiEndpoint = "https://www.myaddress.com/api/"; var getVersion = $.ajax({ url: apiEndpoint + "version/", dataType: "JSON", username: "myuser", type: "GET", password: "mypass" }); ...

NS_Binding_Aborted issue encountered with AJAX operation

I recently encountered an issue with a link that is supposed to trigger a request to the web server upon clicking, followed by a redirection upon successful execution. My approach involved using ajax for this purpose, however, I have been encountering an N ...

Why is it necessary to use '!important' to change the color of my navbar?

Hey there! I'm diving into the world of bootstrap, CSS, and HTML for the first time and I'm looking to spice up my navbar by changing the text color. However, I want to achieve this without resorting to the use of "!important". Take a look at my ...

JavaScript code successfully launched a new window displaying a PDF file

Is there a way to prevent a blank browser window from opening when loading a PDF file using JavaScript onload action? Currently, when I open a PDF in Adobe Reader through a JavaScript function on page load, a new blank browser window appears in addition to ...

Having trouble with aligning text using the span tag?

I'm attempting to create a line for pricing where the text-align is aligned differently for each item - left, center, and right. Despite using text-align, I am unable to maintain all three items on the same line. Is there an alternative solution or w ...

Tips for transferring data from JavaScript to a PHP page without having to refresh the page

Hello everyone, I'm looking for some assistance on how to pass a value to PHP using JavaScript without reloading the page. What I'm aiming for is that when I input a value in a text box named num1, that value will be sent to available.php. Thank ...

Tips for making a scrollable container that allows its contents to overflow without clipping?

Currently working on implementing a horizontal card row for my website with a unique hover effect - the cards lightly rotate and raise on hover. Here is a preview: https://i.sstatic.net/eDQ59.gif To make this row responsive, I added overflow-x: auto; to e ...

What could be the reason for the checkbox not being selected in a React component

I'm currently working on integrating an autocomplete feature with checkboxes. Learn more here https://i.stack.imgur.com/YtxSS.png However, when trying to use the same component in final-form, I'm facing issues with checking my options. Why is t ...

Equalizing column heights in Bootstrap layouts

It seems like a straightforward issue, but I'm having trouble finding a solution. I am utilizing Bootstrap5 for this project. You can find the complete code here : Due to some problems with Codeply, I have also uploaded it on jsfiddle. https://jsf ...

Is the custom CSS being overridden by the bootstrap.css.map file?

I am currently working with Bootstrap 4 and I am attempting to adjust the padding for the navigation links within the navbar using my own custom CSS file: .nav-link { padding: 0.15rem; } However, the styling that is being applied comes from the followin ...

Ensure that Javascript waits for the image to be fully loaded before triggering the Ajax function

function addResource() { var imgIndex = getIndexByImageID(currentDraggedImgID); var newImageID = resourceCollectionSize.length; // Insert the image $('#thePage').append('<img alt="Large" id="image' + newImageID + &a ...

What is the best way to format FormControl for proper spacing?

<FormControl fullWidth component="fieldset" inputRef={register({ required: true })}> <FormLabel component="legend">Format</FormLabel> <RadioGroup row aria-label="format&q ...

Utilize Webpack 4 to ensure JQuery is accessible universally throughout the entire website

Is there a better way to globally include jQuery in my Webpack 4 website for optimal performance? Currently, I am npm installing jquery and manually adding it to every js file using: import $ from "jquery"; I know this method is not ideal. I have explore ...