Using jQuery to dynamically change the CSS color based on the background-color of a checkbox label

When a checkbox is selected, the function below runs to change the text color to white or black based on the darkness of the background color. However, the third checkbox should trigger this change to white but currently does not.

function isDark(color) {
    var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
    return (
      (match[1] & 255) + (match[2] & 255) + (match[3] & 255) < 3 * 256 / 2
    );
}

The following code snippet attempts to execute this logic:

label.css(
  "color",
  isDark(label.css("background-color")) ? "white" : "black"
);

A fully-functional example can be found on CodePen at the link below:

https://codepen.io/moofawsaw/pen/RmZWaL

// JavaScript code block here
// CSS styles go here
// HTML markup goes here

Answer №1

Latest Update

An additional demonstration has been included. I developed a small plugin that adds animation to elements with classes .dot and .cancel. Check out Demo 2 for more details


"However, the third checkbox is intended to have dark text color which should change to white, but this feature is not working as expected."

The issue lies in the fact that isDark() function was malfunctioning due to incorrect implementation. The data attribute data-color of the third button had a value of "blue" instead of rgb(0,0,255), causing the function to return false. In addition, there were multiple syntax errors in the code snippet, including:

function isDark(color) {
  var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
  return (match[1] & 255) + (match[2] & 255) + (match[3] & 255) < 3 * 256 / 2;
}
  1. Extracting numbers using regex from an arbitrary source like data-color is unreliable. Instead, keep the numbers directly such as data-rgb="0,0,255".

  2. The usage of .exec() method will only return one string array instead of individual matches due to the nature of the regex used. Therefore, variables like match[1], match[2], etc., do not exist.

  3. The portion ... & 255) and the calculation 3 * 256 / 2 are flawed concepts. Moreover, 385 (sum of rgb(128,128,128)) does not represent a valid argument for color darkness.

Therefore, the original code underwent significant changes especially with the isDark() function being reduced to just two lines while addressing various discrepancies. Other parts of the HTML, CSS, and JavaScript were also optimized for better efficiency.

New Features Demo

(previews ommitted)


Additional Functionalities Showcase

(preview omitted)

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

Reducing image size using CSS can result in blurry images on multiple web browsers

Encountering challenges with downscaled images in multiple browsers... The images must be downscaled to adapt to the browser size. Here is the code snippet: #pic-holder img { -moz-transform: rotate(0deg); /*image-rendering:-webkit-optimize-contras ...

Limit the container's height to be no more than the height of the

Seeking input on good and bad practices in CSS/HTML/jQuery, I recently asked a question about determining when it is appropriate to use jQuery to set container dimensions. The responses I received were helpful (view them here). Realizing that jQuery may n ...

Clear out any unnecessary white space beneath the content on your webpage

I am relatively new to Web Development and currently following Colt Steele's udemy course. I have been working on a landing page, but as I try to set the height of HTML to 100%, it leaves whitespace at the bottom. After some research, I suspect that t ...

How to switch around div elements using CSS

There are two unordered list items in a container div and one swap button. When the swap button is clicked, the order of items needs to change. This functionality can be achieved using the following swap function. var ints = [ "1", "2", "3", "4" ], ...

Implementing a click event to apply an overlay over a div using jquery

When hovering over image1, image2 should appear with a close (X) button in the bottom right corner. Clicking the close button will make image2 disappear and show image1 again. ...

Encountering an 'Uncaught TypeError' with Tumblr API due to undefined property 'type' not being read

I have multiple feeds on my website, each fetching posts from various tags. The first feed is functioning properly, but the 2nd and 3rd feeds are displaying the following error: Uncaught TypeError: Cannot read property 'type' of undefined All ...

What strategy should be employed to ensure that Javascript is operational upon completion of page loading?

I'm facing a challenge with running my JavaScript on my ASP.NET webform page. It seems like the elements are not fully loaded when the script runs, which could be causing issues. How can I use jQuery to ensure that my script is placed at the bottom of ...

Enhance your iPad's design with a stylish div box-shadow

I'm in the process of developing a touch-optimized web application. As part of the design concept, I've implemented some visually appealing div elements that respond to clicks or touches for easy navigation. While this functionality works perfec ...

How to Center a DIV both Vertically and Horizontally with CSS Positioning?

I'm currently working on a webpage layout where I want to have a main div centered horizontally with three smaller divs inside, aligned both vertically and horizontally with equal spacing. I tried using margin: auto on an empty div to center it in the ...

Horizontal JQuery Slider for CategoriesDiscover the smooth, sleek category navigation with

Looking to create a sliding horizontal menu with various categories using a clever div layer setup. The goal is to have one fixed-width div containing another wider div, with only a portion of the second one visible at a time. Encountering two challenges ...

Utilizing AJAX to dynamically load a jQuery Background Slider

I have a challenge of creating a website that updates internal links without refreshing the page. The navigation will remain consistent while the content is loaded using jQuery .load(). Everything seems to be working well except for the issue with loading ...

Exploring the world of CSS and designing layouts using multiple div elements

Upon reviewing this website, I must admit it is getting close to what I envision. However, being a perfectionist and new to HTML and CSS, I find myself struggling to achieve the desired outcome. The layout consists of two divs named topred and top yellow, ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

Implementing sound playback within an AJAX response

Recently, I implemented a jQuery code to automatically refresh a specific div. This auto-refresh feature uses AJAX to generate notifications whenever there is a new request from a client, similar to social network notifications. I even incorporated music f ...

Transmit JSON data to a node.js server

Currently, I am in the process of developing an application that involves a RESTful Node.js server and a client-side built with JavaScript/Zepto. I have encountered an issue when trying to send a JSON string from my client to the server. Below is the code ...

Switching the class again does not result in an icon change

When a button is clicked, a class of "fa-minus" is added to a newly appearing div. If the fa-minus class is then clicked, the text decoration changes to a "line-through". Additionally, I want the fa-minus icon to change to fa-plus (which will undo the line ...

Utilizing JQuery to track DIV clicks

I am encountering an issue with DIV clicks while using JQuery. I need guidance on this problem. Within my HTML, there are three designated DIV elements: <html> <body> <div id="overviewContainer"> <div id="firstContainer"></ ...

Error message: "Invalid syntax detected while using the jQuery UI select plugin"

While utilizing jquery 1.8.1, I encountered a particular error message related to the jquery ui select plugin within the second code snippet. The specific error is shown below: Uncaught Error: Syntax error, unrecognized expression: li:not(.ui-selectmenu-g ...

Classify JavaScript Array Elements based on their Value

Organize array items in JavaScript based on their values If you have a JSON object similar to the following: [ { prNumber: 20000401, text: 'foo' }, { prNumber: 20000402, text: 'bar' }, { prNumber: 2000040 ...

"Apply a class to a span element using the onClick event handler in JavaScript

After tirelessly searching for a solution, I came across some answers that didn't quite fit my needs. I have multiple <span id="same-id-for-all-spans"></span> elements, each containing an <img> element. Now, I want to create a print ...