How can I make my Background change on click using hexadecimal color codes?

I am struggling with changing the background color of an html document using a button click.

While colors like "yellow, "blue", and "red" work perfectly, I encounter an issue when trying to use hexadecimal colors such as "#000000".

The if-condition doesn't seem to recognize the hexadecimal color and defaults to the else function instead.

Interestingly, substituting "#000000" with "black" makes the function work as intended and the background turns red.

If you would like to see the code in action, check out the working sample on jsfiddle:

https://jsfiddle.net/c2gv9x01/

<button>COLOR SWITCH</button>

<script>
window.onload=function(){
    document.querySelector("body").style.backgroundColor = '#000000';
    document.querySelector("button").addEventListener("click", color);
}

function color() {

    if (document.querySelector("body").style.backgroundColor == '#000000') 
{document.querySelector("body").style.backgroundColor = 'red'; }


     else {document.querySelector("body").style.backgroundColor = '#000000';}
}
</script>

Answer №1

There are numerous variations in string representations for a single color, so relying solely on matching the hex color string may not be effective since it might not reflect what your browser is actually using:

window.onload = function() {
  let body = document.querySelector("body")
  body.style.backgroundColor = "#000000"
  console.log(body.style.backgroundColor) // rgb(0, 0, 0) in most browsers
}

It's advisable to avoid direct color matching whenever possible; different browsers may interpret colors differently, hence converting from hex to rgb won't always yield accurate results. Instead, assign a specific classname to the element that defines the required colors and check for the presence of that classname:

window.onload = function() {
  document.querySelector("body").classList.add("black")
  document.querySelector("button").addEventListener("click", color);
}

function color() {
  let body = document.querySelector("body")
  if (body.classList.contains("black")) {
     body.classList.add("red")
     body.classList.remove("black")
  } else {
     body.classList.add("black")
     body.classList.remove("red")
  }
}
.black {
  background-color: #000
}

.red {
  background-color: #F00
}
<button>COLOR SWITCH</button>

If you absolutely have to match a color, the safest approach would be to create a temporary element with the same background color, extract the color from both elements, and compare them to ensure accuracy across different string representations used by various browsers.

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

The post request with Postman is functional, however the AJAX post request is not working. I have thoroughly reviewed the client-side JavaScript

I encountered a problem with an endpoint designed to create an item in my application. Sending a POST request through Postman works perfectly fine, as I am using Node.js and Express for the backend: router.post("/", jwtAuth, (req, res) => { console.lo ...

At times, Express.js may display an error message stating "Cannot GET /"

My objective is to have http://localhost:3000/app display myFile.html and http://localhost:3000/api return "It worked!". I currently have two files set up for this: App.js: const http = require('http'); const fs = require('fs&apo ...

Generating dynamic @returns annotations in JSDoc based on the value of @param

How can I properly document the function in order for vscode-intellisense to recognize that getObject("player") returns a Player type and getObject("bullet") returns a Bullet type? /** * @param {string} type * @return {????} */ function getObject(type ...

Utilizing the getJSON Method to Automatically Fill a Dropdown Selection Element

I am looking to populate a dropdown select menu with bank names and IIN numbers obtained from the following JSON: JSON Data : {"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Ba ...

working with json files in node.js

I have encountered an issue with manipulating a JSON file using Node.js. Here is the scenario: { "joe": { "name": "joe", "lastName": "black" }, "matt": { "name": "matt", "lastName": "damon" } } Now, I n ...

What is the best way to define the relative path and folder paths in HTML and CSS when working in Visual Studio 2012?

Working on a basic HTML project that includes css and javascript. Within the project folders named css, scripts, and images are used for organization. The project structure can be seen in the provided image. https://i.sstatic.net/OwCSL.jpg The issue that ...

Express application failed to deploy due to boot timeout error R10

After researching extensively on Stack Overflow and various other websites, I have been unable to solve a problem with my small Express app using ES6 syntax. Upon deploying it to Heroku, I encountered the following error: LOGS : 2021-04-09T12:14:14.688546 ...

The property 'apply' is trying to be accessed but is undefined and cannot be read

Not being an expert in frontend development, I've hit a roadblock on what seems like a simple issue. I'm attempting to load one set of nodes from a JSON file successfully, but when trying to add new nodes from another JSON file, I encounter this ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...

Ways to emphasize an HTML element when clicked with the mouse

Can JavaScript be used to create code that highlights the borders of the HTML element where the mouse pointer is placed or clicked, similar to Firebug, but without needing a browser extension and solely relying on JavaScript? If this is possible, how can ...

Why are the indicators and controls for Twitter-Bootstrap 5 carousel not functioning properly?

Currently, I am working on developing an ecommerce website using the Django framework. However, I am facing challenges with making my bootstrap carousel function properly. When trying to interact with the indicators and controls, nothing happens as expect ...

Deactivate numerous buttons with the help of jQuery

Within my MVC view, I have a Razor foreach loop that generates table rows with buttons: @foreach (var item in Model) { <tr> <td>@item.Id</td> <td> <button id="btn" class="button btn-primary" type= ...

Discovering the point of exit for a mouse from an image

Visit this website to see the effect in action: I am curious about how the image scrolls into and out of the direction where the mouse enters and leaves. Can you explain how this is achieved? ...

What is the process behind Stackoverflow's "Congratulations, you've earned a new badge" popup window?

Possible Duplicates: Custom notify box similar to StackOverflow Creating popup message like StackOverflow How does StackOverflow implement the "You earned a new badge" window? (the orange one that pops up at the top of the screen, I believe it&ap ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

Simple steps to trigger a PHP page from a JavaScript page by utilizing express functions

Currently, I am attempting to showcase a PHP page using JavaScript with express functions. Here is an illustration of the code: var express = require('express') var app = express() app.get('/', function (req, res) { res.send(' ...

Determining the percentage between two elements using Bootstrap 4's range slider

I've been searching everywhere but haven't found a solution. I am trying to implement Bootstrap 4.5's range slider to distribute the % difference between Client and Company, ranging from 1% to 100%. However, I am struggling with the jquery/j ...

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

The classification of rejected promises in Typescript

Is it possible to set the type of rejection for a promise? For example: const start = (): Promise<string> => { return new Promise((resolve, reject) => { if (someCondition) { resolve('correct!'); } else { ...