Colorful Background Switcher

I am looking to create a set of buttons representing the colors ROYGBV. I want to use JavaScript to apply a function that will change the background color when each button is clicked. The current code I have seems too lengthy. Can someone assist me with this?

function redColor(){document.body.style.backgroundColor="red";}
function orangeColor(){document.body.style.backgroundColor="orange";}
function yellowColor(){document.body.style.backgroundColor="yellow";}
function greenColor(){document.body.style.backgroundColor="limegreen";}
function blueColor(){document.body.style.backgroundColor="blue";}
function indigoColor(){document.body.style.backgroundColor="#4B0082";}
function violetColor(){document.body.style.backgroundColor="violet";}

Answer №1

To simplify the process, you can create a single function that accepts a color argument such as:

function changeBackgroundColor(color) { document.body.style.backgroundColor = color; }

This function can be used like this:

changeBackgroundColor("red");
// or
changeBackgroundColor("hsla(180, 80%, 80%, 0.8)")

If you want more flexibility, you can modify the function to also accept the element you wish to style:

function setCustomBgColor(elem, color) { elem.style.background = color; }

setCustomBgColor(document.body, "blue");

Instead of creating separate functions for each styling task, it is more efficient to have a function that can handle multiple CSS properties at once:

const applyStyles = (element, styles) => typeof styles === "object" ? Object.assign(element.style, styles) : element.style.cssText = styles;

// Example usage:

applyStyles(document.body, {
  color: "red",
  background: "blue",
  fontSize: "2rem"
});

// Or use template literals for inline styling:

applyStyles(document.querySelector("#someElement"), `
  color: red;
  background: blue;
  font-size: 2rem;
`)

Answer №2


function changeElementColor(color, selector) {
  let selectedElement = document.querySelector(selector);
  selectedElement.style.backgroundColor = color;
} 

// Example of usage in HTML:
<button onclick="changeElementColor('blue','header')">Blue</button>
<button onclick="changeElementColor('yellow','header')">Yellow</button>

Answer №3

Here is an innovative approach

While it may be more extensive than simply passing a color to a function, this method introduces some intriguing techniques to explore

const colors = {
  "red": "red",
  "orange": "orange",
  "yellow": "yellow",
  "limegreen": "limegreen",
  "blue": "blue",
  "hex": "#4B0082",
  "violet": "violet"
};
const colorKeys = Object.keys(colors);
const colorEntries = Object.entries(colors);

const createStyleSheet = () => {
  let head = document.querySelector('head'),
    style = document.createElement('style'),
    css = colorEntries
    .map(([name, color]) => `.${name}-bc { background-color: ${color}}`)
    .join('\n');
  css += '.colorButton { text-transform: capitalize;}'; // Uppercase first letter of button text
  style.type = 'text/css';
  style.appendChild(document.createTextNode(css))
  head.appendChild(style);
};
window.addEventListener('DOMContentLoaded', () => {
  createStyleSheet();
  const bodyCL = document.body.classList;
  const colorDiv = document.getElementById('colorDiv');

  colorDiv.innerHTML = colorEntries
    .map(([name, color]) => `<button class="colorButton ${name}-bc" value="${name}">${color}</button>`).join('');
  colorDiv.addEventListener('click', (e) => {
    const tgt = e.target;
    if (!tgt.matches('.colorButton')) return; // not a button
    colorKeys.forEach(color => bodyCL.remove(`${color}-bc`)); // remove previous
    bodyCL.add(`${tgt.value}-bc`);
  });
})
<div id="colorDiv"></div>

Answer №4

To streamline the function, you can do the following:

function changeBackground(color){
  document.body.style.backgroundColor = 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

Which is better for your website: SSG vs SSR?

Currently, I am diving into Nextjs and constructing a website using this framework. The site includes both public pages, protected routes (like user dashboard, user project details, and general user data), as well as product pages. I have been pondering h ...

What is the correct way to transfer session variables to an email?

Currently, I am working on a project that involves extracting and sending data stored in the session variable $_SESSION['favourites']. To achieve this, I initially utilized the print_r function with the parameter set to true. The output generate ...

Unable to detect HTML special characters in the text

In my current task, I am facing the challenge of matching two URLs. One URL is retrieved from a MySQL database, while the other one is sourced from an HTML page. When comparing both URLs as strings using Regex, the result shows match.Success = false. Despi ...

Struggling with displaying MySQL data in JSON format using Highcharts

Currently, I am attempting to display data from a PHP file on an area graph by using the example found here. Initially, all the data was commented out before being passed to the array. Now, my focus is solely on displaying one portion of the data. I suspec ...

The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin. I attempted to split the string into an array, but the resulting key/values were not as expected. For exampl ...

If there is no data defined, then it is necessary for at least one attribute to be present in the

I am encountering an issue while attempting to utilize Google Cloud's Pub/Sub API to send messages to topic subscribers. The error message I am receiving is "If data is undefined, at least one attribute must be present.". My intention is to integrate ...

Sending an Array from JavaScript to Asp.net Core

Below is the javascript code that invokes the asp.net CustomHeatMapDate function $('.Date').change(function () { var data = []; console.log(); var dateList = [{"Date":"03/23/2016"}, {"Date":"03/24/2016"}]; $.ajax({ async: ...

Responsive Design and Advertising with CSS Media Queries

For my application, I am utilizing Twitter's bootstrap (responsive) css. My goal is to incorporate banner ads in the sidebar section. However, due to different media query settings, the sidebar's width will vary, resulting in the need for the ban ...

JavaScript's failure to properly handle UTF-8 encoding

Here is a snippet of code that I found on Stack Overflow and modified: <?php header('Content-Type: text/html; charset=ISO-8859-1'); $origadd = $_SESSION["OriginAdd"] // $_SESSION["OriginAdd"] contains the value "rueFrédéricMistral"; echo $o ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Is there a way to automatically generate additional text fields based on the user's input?

Is there a way to dynamically add multiple text fields for color and choose design based on user input? For instance, if the user enters 5 in the quantity field, how can I replicate the color and choose design fields 5 times? Additionally, how should I st ...

Tips for retrieving data from a JSON array

I have a JSON object that looks like this: var obj={ "address":{ "addlin1":"", "addlin2":"" }, "name":"sam", "score":[{"maths":"ten", "science":"two", "pass":false }] } Now, when I attempt to m ...

Validate the date selected in a dropdown menu using JavaScript

I'm still relatively new to Javascript, just working my way through some tutorials. I have three select boxes in my HTML form as shown below. HTML Form: <table> <form id="enrolment" name="enrolment" onsubmit="return datevalidate();" action ...

Resolved: Angular JS resolves circular dependencies

I encountered a Circular dependency issue while attempting to make a http.post call in a http interceptor: Circular dependency found: $http <- Ace <- authInterceptor <- $http <- $templateRequest <- $compile I understand the problem, but I ...

Use Google script to input drop down options directly into a Google spreadsheet

After gathering coding advice from various StackOverflow examples, I've hit a roadblock while attempting to take my script to the next level. The task seems simple enough, but for some reason, I just can't figure it out. Here's the situati ...

Unable to append Jquery attribute to a div component

My code snippet is creating a div with specific classes and elements: '<div class="ctrl-info-panel col-md-12 col-centered">'+ '<h2>You do not have any projects created at the moment.</h2>'+ '<div id="t ...

Tips on saving checklist values as an array within an object using AngularJS

I need help with storing selected checklist items as an array in a separate object. I want to only store the names of the checklist items, but I am struggling to figure out how to achieve this. Below is the HTML code: <div ng-app="editorApp" ng-contro ...

What is the best way to replicate a div's background color using an image within the body element?

I am looking to achieve a layout similar to the one below: https://i.sstatic.net/1cOYw.png The dark grey color represents the sidebar, but I want to use this color as a repeating vertical image in the body element without covering the footer (light gray) ...

I am looking to integrate a predefined equation using JavaScript

I need help implementing a specific formula in JavaScript that involves dealing with 5 input fields. Below is the HTML code (apologies for the language, it is in a different locale): <div class="row" style="padding:10px 12px;"> &l ...