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

Submitting a form using jQuery and receiving data in JSON format

Utilizing the Jquery form plugin, I am sending my form via ajax. The PHP script on the server side processes the form data and provides a JSON string in this specific format: {"error":true,"message":"The username or email already exists. Please try agai ...

The process involves transferring information from a specific div element to a database. This particular div element obtains its data after receiving an appended ID

It's a bit complicated, but I'm working on creating a tag system. I'm fetching data from a database with an AJAX call using the "@" symbol. Everything is working fine - the tags are being generated, but I'm having trouble retrieving and ...

The form fails to submit even after the validation process is completed

My current dilemma involves the validation of an email and checkbox to ensure they are not empty. Although it initially seemed to work, after filling in the required fields and checking the box, I still receive a warning message (.error) and the form fails ...

Error encountered: syntax error, unexpected token while executing a basic AJAX request

Hello, I am new to AJAX and javascript, so please be patient with me. I am trying to pass a variable (document.getElementById('txtSearch').value) from my AJAX to PHP. Here is the code I attempted: $("#btnSearch").click(function() { ...

Having trouble uploading files with AJAX in CodeIgniter?

Here is the code for my form in view: <?php $attributes = array('id' => 'myForm'); echo form_open_multipart('', $attributes); ?> <div class="form-group"> <label for="image">Main ...

Box Pattern with Pop-Up Modal

Check out the grid of squares I've coded below: <div class='square-container'> <div class='square'></div> <div class='square'></div> <div class='square'></div& ...

The Jquery ajax function fails to execute after upgrading the framework version from 3.5 to 4.0

After testing with alert, I am facing an issue where the ajax call is not working in my aspx.cs file when switching from .NET framework 3.5 to 4.0. The ajax function being used is: function GetCustomers(pageIndex) { $.ajax({ t ...

What is the correct way to invoke a function within jQuery?

There must be a straightforward solution to what appears to be a simple and regular task. Inside the $(document).ready() function, I aim to invoke a function with a jQuery object - specifically without attaching it to an asynchronous event like mouseover ...

The simplest method for integrating SASS within your WordPress website

While I usually work with CSS, I've decided to tackle SASS in order to improve my efficiency. I successfully converted a CSS file from .css to .scss and it still works as expected. However, when I added variables, they didn't function properly. ...

Utilize jQuery to refresh the database with the information retrieved from the ajax-request

I am attempting to update the database. This is what I am doing From my JavaScript code var data = { "jobid": $('#jobid').val(), "names": $('#names').val(), "scripttype": $('#testscripts').val() }; var msg=""; f ...

The AngularJS REST service fails to function properly when attempting to load page content through Ajax requests

My REST service retrieves data from the back end and displays notifications to the user when they click the notification button. Initially, the notification div is hidden, but when the button is clicked, it will display with the REST data. However, I have ...

Issue with making a call to retrieve an image from a different directory in ReactJS

This is how it appears <img className='imgclass' src={"../" + require(aLc.value)} alt='' key={aLc.value} /> I am trying to create a path like ../m/b/image.jpg, where aLc.value contains the path /m/b/image.jpg. I need to add only ...

Different browsers have varying ways of handling transition end callbacks with AddEventListener()

Each browser has its own transition end callback. Therefore, I find myself needing to use addEventListener() for each one. addEventListener('transitionend', function() { // code here }); addEventListener('webkitTransitionEnd', funct ...

Refine the JSON data to only include the values you need

I've been spending a considerable amount of time on this challenge, but I'm facing difficulty in solving it. The issue at hand is that I have a JSON file that I am fetching from a URL, and my objective is to create a filter that displays only nam ...

Exploring the world of mouse events in Typescript using JQuery, all the while maintaining strict typing regulations

I'm currently working on a project that involves using JQuery in Typescript. One challenge I'm facing is passing a mouse event from a JQuery element to a wrapper class. Here's an example of what I'm trying to achieve: import * as $ fro ...

How can I delete the global styles defined in _app.js for a particular component in Next.js?

While working with NextJs and TailwindCSS, I encountered an issue where all the extra styles in my globals.css file were causing some trouble. Although it is recommended to import it at the top level in the _app, I tried moving it down to the "layout" comp ...

The showdown: JQUERY $(document).click versus $(document).ready

$(document).ready(function(e) { if ($('#sidebar').hasClass('active')) { $('#dismiss, .overlay').on('click', function() { $('#sidebar').removeClass('active'); $('.overlay&apo ...

Is there a way for me to adjust the window's placement?

Currently utilizing Jquery to launch a new Telerik window, as shown below: var win = $('#myWindow').data('tWindow'); win.open(); With the knowledge of the mouse position (x,y), my goal is to initiate the window at that exact location. ...

Conceal the URL and any parameters upon successful completion of AJAX request

In my ajax js code, the solonreport.jsp file returns a URL link that connects to a local report server and generates an Excel report. However, when using this link with the window.open(json.url) function, the link and parameters are visible to the user. ...

Tips for Implementing Multi-Level/Nested in Ajax Requests

I am currently developing a user-friendly web application with intuitive multi-level options that loads new content without the need to refresh the entire page. This is how my structure looks: /index.php /schools.html /colleges.html Within schools.html, ...