Is it possible to overlay color on top of a div background? (i.e. modify div color without altering the 'background-color' property)

Can you apply a color "on top of" a div's background? I'm looking to change the displayed color of a div without altering the 'background-color' value.

I need to keep the background-color for comparison when divs are clicked:

var pick1 = false;
var pick2 = false;
var id1;
var id2;

$('.card').click(function(){

    if(pick1) {
        pick2 = $(this).css('background-color');
        id2 = $(this).attr('id');
        if(pick1 == pick2 && id1!=id2) alert('Correct');
        else alert('Incorrect');

        pick1 = false;
        pick2 = false;
    } else {
        pick1 = $(this).css('background-color');
        id1 = $(this).attr('id');   
    }
});

The objective is to hide the divs with a grey color, only revealing them upon being clicked: http://jsfiddle.net/94jerdaw/WJQkA/4/

EDIT:

How can the grey color be removed by clicking a div? See here: http://jsfiddle.net/94jerdaw/29TCZ/3/

Answer №1

It's a bit unclear what you're aiming for, but have you considered using the :after pseudo-element?

.card {
    position: relative;
}
.card:after {
    content: "";
    display: block;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: black;
}
.card:hover:after {
    display: none;
}

For a live demonstration, check out this example.

You can also swap out :hover with a specific class and toggle it on and off as needed.

Answer №2

First off, altering a div's background-color necessitates changing its CSS background-color property. How else could it be done?

If your goal is to retain the last background color (for a specific action or to revert back to it later), then store it in hidden input variables.

Afterwards, you can utilize these values wherever needed.

Furthermore, if you wish to extract the background-color property and showcase it as text within the div, it can be achieved effortlessly.

var color = $('#selector').css('backgroundColor');

, however this will provide the RGB value. For hex representation, employ the following convenient methods:

var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");

//Function to convert hex format to an RGB color
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

referenced from here

Update,

Your current divs are structured like this:

<div id="a1" class="card"></div>
<div id="a2" class="card"></div>
<div id="a3" class="card"></div>
..
..

Given that you intend to assign a unique color to each of these divs, modify them using JavaScript within your loop to resemble this:

 <div id="a1" class="card" data-color-index="1"></div>
 <div id="a2" class="card" data-color-index="2"></div>
 <div id="a3" class="card" data-color-index="3"></div>

Now, when clicking on a specific div, retrieve its index and select the corresponding item from your colors array. Since you are modifying the original array using splice, I created a duplicate for future usage.

You can access any element's attribute data-color-index via jQuery as demonstrated below:

   $('#selector').data('color-index');

View this snippet. It accomplishes the desired functionality.

Answer №3

According to Manish, altering the appearance of a div requires changing its CSS properties. Yet, there are sneaky tricks to achieve the same effect. One clever method involves creating child divs within colored squares that cover the entire area and setting their color to grey. By toggling the display property in CSS, you can show or hide these overlay divs.

Instead of repeatedly checking the DOM for colors, I suggest storing the color values in JavaScript and referencing them when a square is clicked. This approach helps maintain separation between logic and presentation :)

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

Angular: Assigning a key from one variable to a value in another

I am currently facing a challenge with rendering a form on a page using ng-repeat, where the data for this form is dynamically fetched from a request. Within this data, there is a nested array called "categories" which contains IDs. I want to display the n ...

The fading effects are not functioning as expected in the following code

Hey there, I'm not the most tech-savvy person, but I managed to come up with this code for page redirection. Unfortunately, I couldn't quite get the fade out and fade in effects to work properly when executing it. If anyone out there can help me ...

Troubleshooting Problem with jQuery Submit on Chrome in ASP.NET MVC 3 Ajax.BeginForm

Hey everyone, I've been trying to solve a problem all morning without any luck. Here's the issue -> I have an Ajax.BeginForm that is triggered by a checkbox using jQuery: <% using (Ajax.BeginForm("Edit", "Products", ...

history.push() function is ineffective within a JavaScript file that does not contain a class

I've been delving into React and encountering an issue with the history.push("/dashboard") method, it's not functioning as expected. import axios from "axios"; import { GET_ERRORS, GET_PROJECT, GET_PROJECTS } from "./types"; export const createP ...

Activation of navigation buttons in the Vue Full Calendar control the movement to the next and previous

In my current project, I am utilizing https://www.npmjs.com/package/vue-full-calendar. However, I have encountered an issue when trying to receive callbacks or triggers from the next and previous buttons on the calendar. My backend API is structured aroun ...

What is the best method for sending the styled and checked option via email?

Just finished customizing the checkboxes on my contact form at cleaners.se/home. Here's my question: If I select "telefon," how can I ensure that this option is sent to my email? In Contact Form 7, I used to simply type a shortcode. Is there a simila ...

Connect-busboy causing NodeJS issue: TypeError - the method 'on' cannot be called on an undefined object

Recently I encountered an issue with a piece of my code: router.route("/post") .get(function(req, res) { // ... }) .post(authReq, function(req, res) { // ... // Get uploaded file var fstream; req.pipe(re ...

Adding individual flag icons for each country in your Datatables can be a significant enhancement to

Below is the code snippet in JavaScript with flags: <script type="text/javascript"> $(document).ready(function() { var dataTable = $("#example").DataTable( { processing: true, bSort: false, ...

What is the best way to call a JavaScript function within a PHP echo statement that outputs a <div> element?

Having trouble echoing this PHP code due to issues with single quotes, causing the HTML to end prematurely. Any suggestions on how to fix this? function button($conn){ $sql = "SELECT * FROM table"; $result= mysqli_query($conn, $sql); while($r ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...

Dynamic and operational icons accompany the AngularJS search input field

Currently, I am delving into the world of AngularJS and experimenting with a search box. Within this search box, I want to incorporate three icons: a magnifying glass, a cross, and a spinner. For the first scenario, I envision the magnifying glass appearin ...

Is there a way for my JavaScript file to manipulate an EJS variable?

In the index.ejs file, I declared an ejs variable named "complete" which verifies whether a user has completed a journal entry by using the following code: <% if (complete == false) { %> <button class="new_journal">Fill Out Journal<i cla ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

What is the process for assigning a CSS class to a div element that is generated by react's render() function?

In React, I am encountering an issue where the css class I want to set on the div returned from render is being removed. This problem even persists when I try nesting another div inside the first one and setting the class on the enclosed div. Has anyone ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

JavaScript function to add or subtract

I need to include additional inputs for "+ and -" 60mm and 120mm in my function. How can I achieve this without turning all of them into separate functions? <template> <card class="card"> <h2>Measurement</h2> <form&g ...

Ensure that the height of the flex body is set to 100% within the ReactNative View

Within my React Native app, I have constructed the following view: <ScrollView style={{ width: 250, height: '100%', backgroundColor: '#000000' }}> <SafeAreaView style={{ flex: 1, flexW ...

Contrasting deleting a node_module folder with running npm uninstall to remove a specific package

Do manual deletion of a package directly from the node_modules folder and running npm uninstall really make any difference, considering that npm just deletes the package anyway? ...

Tips for determining the presence of a query string value using JavaScript

Is there a way to detect the presence of q= in the query string using either JavaScript or jQuery? ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...