Setting a CSS Variable with the Help of jQuery

I need help with changing the background color of a specific .div element when it is clicked on. I want the color to be a variable that can be changed by the user, and this change should occur when the document is ready.

Currently, I am using a CSS variable called '--main-color' for this purpose, but I am struggling to find a jQuery solution that involves using '$(this)'.

Is there a way to apply a custom CSS property or variable with a .click() function in jQuery?

$(document).ready(function(){

// CREATE GRID
for (i = 0; i<1152; i++) {
var board = document.createElement('div');
board.className = 'grid';
board.addId = 'color'
document.getElementById('container').appendChild(board);
};
// END CREATE GRID

  // HOVER AND CLICK FUNCTION //
      $('#color-picker').colorpicker().on('changeColor', function(ev){
    var choice = ev.color.toHex();
        document.body.style.setProperty('--main-color', choice);
});

  $('.grid').hover(function(){
        $(this).click(function(){
        $(this).css('background-color', 'var(--main-color)');
});
});
// END HOVER AND CLICK FUNCTION


});
body {
background-color: #222;
margin: 0;
padding: 0;
box-sizing: border-box;
font-family:'Patua One', cursive;
color: #FFF;
--main-color: #000;
}
*{
background-color: #222;
margin: 0;
padding: 0;
box-sizing: border-box;
font-family:'Patua One', cursive;
color: #FFF;
}

#title {
font-family:'Revalia', cursive;
font-size: 3em;
color: #FFF;
text-align: center;
}

.menu {
float:left;
    clear: left;
    width: 300px;
    margin-top: 5%;
    margin-left:5%;
}

#container {
height: 800px;
width: 800px;
border: 1px solid #424242;
margin-left: 30%;
margin-top: 5%;
background-color: #FFF;
}

.grid {
height: 20px;
width: 20px;
border: 1px dotted #424242;
background-color: #FFF;
display: inline-grid;
}

div.grid:hover{;
background-color: var(--main-color);
}

.active {
background-color: var(--main-color);
}

.form-control {
    display: block;
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #FFF;
    background-color: #222; 
    background-image: none;
    border: 1px solid #F85658;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}

Answer №1

Add a color to a specific class and switch the class on and off.

document.querySelector('div').addEventListener('click',function() {
  this.classList.toggle('color');
})
body {
  --main-color: #000;
}
.color {
  background-color: var(--main-color);
  color: white;
}
<div>div</div>

Alternatively, using jQuery...

$(function() {
  $('div').on('click',function() {
    $(this).toggleClass('color');
  });
});
body {
  --main-color: #000;
}
.color {
  background-color: var(--main-color);
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>div</div>

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 code in the head section is not running as expected

I've been exploring the possibilities of using lambda on AWS in combination with api gateway to create a contact form for a static S3 website, all inspired by this informative blog post: https://aws.amazon.com/blogs/architecture/create-dynamic-contact ...

JavaScript Game Timer

I am working on a countdown timer where I have set the variable seconds to 10. If the seconds reach zero, I want to add 2 seconds to it and stop the program from looping. Can someone please assist me with this? var isWaiting = false; var isRunning = fal ...

Conflict between Angular's ng-repeat directive and Sass styling

Currently, I am working on a project and encountering an issue that is causing some difficulty: In order to create a navigation bar with equally distributed list elements based on the number of items, I am utilizing ng-repeat for data binding and Sass for ...

Sorry, we encountered a snipcart issue: The public API key was not found. To fix this, please ensure that the attribute data-api-key is

I'm experiencing issues with loading Snipcart correctly. It's able to detect the API key on localhost and display the number of items in the cart, but when deployed to Netlify, it briefly shows the item count before displaying the error message: ...

Ways to update the background hue of a selected Navigation Tab?

One of the challenges I am facing in my React Project is with the Navigation Tab from material-ui. The issue I encounter is that the active tab should have a background color, and then revert to its original color when not active. However, the transparency ...

Steps for automatically toggling a button within a button-group when the page is loaded using jQuery in Bootstrap 3

Here is a button group setup: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-default"> <input type="radio" name="environment" id="staging" value="staging" />Staging </label> <label class= ...

Obtain the script's event feedback from the WebView and transfer it to React Native

My HTML script is used to display a module, but I encountered an issue with the eventHandler not responding. How can I ensure that the eventHandler in Web View triggers responses? I am not receiving any logs for the onSuccess, onError, or onClose methods w ...

Building custom directives on AngularJS pages without a specified ng-app module

On some of my basic pages, I don't need to specify a particular application module in the ng-app attribute. However, these pages do utilize some custom directives that I have created. To keep things organized, I have placed all of my directives withi ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

Error: The function updateElement does not exist

Currently, I am facing an issue while trying to update an element in an array by adding an object as a property. This requires user interaction through a modal where the form is filled and then added as a property for a specific node. However, I encountere ...

Ways to enlarge the font size of a hyperlink

I am just starting out with coding and I need to figure out how to increase the font size of my link. <!DOCTYPE html> <html> <head> <style> /* unvisited link */ a:link { color: #FFFFFF; } /* visited link */ a:visited { color: #FF ...

The Google Contacts API is unable to utilize the max-results parameter when making requests via jQuery AJAX

Here is the code snippet I am using: $.ajax({ url: 'https://www.google.com/m8/feeds/contacts/default/full', dataType: 'jsonp', data: { access_token: token, max-results: '5000', alt: 'json' }, success:function(data){ ...

Modifying Data in Another Component in VueJS

I have a classic Vue Component structured like the following: Vue.component('bar', { template: `<div class="bar"></div>`, data () { return { blocks: [ ] ...

The error "navigator.permissions.query is not a defined object" is encountered in the evaluation

Whenever I try to access my website on an iPhone 7, I encounter a frustrating error. The main screen loads without any issues, but as soon as I click on something, a white bank screen appears. I believe this piece of code might be the cause: useEffect( ...

Generate a new object from the contents of a div

Having the HTML structure below: <div id="main"> <div id="myDiv1"> <ul> <li>Abc</li> <li>Def</li> </ul> </div> <div id="myDiv2"> <ul> <li>Ghi</l ...

Update a mySQL table using dynamic input from a table

I'm facing challenges updating a mysql database with a dynamic table that allows me to add or remove rows before submitting the form. While I can make it work with hardcoded values, I struggle when trying to update with a while loop. It just doesn&ap ...

Unusual characteristics of decision-making

Here is a snippet of my JavaScript code: function getSelectedText(){ if(window.getSelection){ select = window.getSelection().getRangeAt(0); var st_span = select.startContainer.parentNode.getAttribute("id").split("_") ...

What is the method to retrieve the exact value of {match.params.id} in React Router?

This is an example of code that I have. However, I am unsure about how to extract the value and utilize it afterwards. class CustomView extends Component { componentDidMount() { var uniqueId = {match.params.id} } render() { ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Utilizing ES6 imports with module names instead of paths

Is there a way to import modules using just their name without the full path? For instance, can I simply use: import ViewportChecker from 'viewport-checker'; instead of import ViewportChecker from '../ViewportChecker'; I'd ...