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

Is there a method to retrieve a value from a node.js server when a div is clicked?

This is the EJS file I've created: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Sart Plug</title> <script src="http://code.jquer ...

Patience is key as you wait for the observable to finish

My methods have dependencies where one method needs to complete before the next can be called. process1(data: string) : Observable<string> { this.dataservice.process(data).subscribe( (response) => { return response. ...

Displaying an RSS feed inside a designated div element

Seeking assistance from all you wonderful individuals for what seems to be a simple problem. Here is the HTML code I am working with: <div id="rssfeed"></div> Along with JavaScript that includes the FeedEK plugin $(document).ready(function ...

What are some strategies for circumventing the need for two switches?

My LayerEditor class consists of two private methods: export class LayerEditor { public layerManager: LayerManager; constructor() { this.layerManager = new LayerManager(this); } private executeCommand() { ...

I'm having trouble with my "alert()" function in Vue.js

I am new to using Vue and I am attempting to trigger an alert function when a button is clicked. However, I keep encountering the error message Uncaught ReferenceError: addTask is not defined. Below are the codes I have written: <template> ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...

Having trouble getting a background image to show up in a table cell when using CSS clear:both?

I am working on an email and I want an image to only show up on mobile devices. To achieve this, I created an empty <td> with a span inside where I styled the span to have a background image. However, my issue is that I want the image to occupy an e ...

Retrieve form input from a servlet using a name attribute such as "input[]"

Looking to retrieve input values from a form on my JSP page where each input shares the same name. Take a look at this JSFiddle Any suggestions on how I can access these inputs from my servlet? I attempted using String[] description = request.getParamete ...

Stopping HTML 5 video playback while transitioning to a different webpage

My website has a layout with a left menu containing video links and a content area where the videos are played. However, I have encountered an issue when switching between videos. Currently, if I click on Video 1 and then decide to watch Video 2 while Vid ...

Unlocking Controller Functions in AngularJS Directives: A Step-by-Step Guide

Here is a sample controller and directive code: class DashboardCtrl { constructor ($scope, $stateParams) { "ngInject"; this.$scope = $scope; this.title = 'Dashboard'; } loadCharts () { // some logic here } } export def ...

Echoing data from an input form is not possible with an associative array

I'm having trouble printing the associative array after inserting data from an input box. Currently, I can only display the latest data entered in the input box. What I really want is to continuously add data to the array and display it every time new ...

Showing information from a table for editing purposes with the use of HTML input tags

As I navigate my way through the complexities of HTML and PHP coding, I’m faced with a challenge in displaying database content on an editable table within my web page. Clicking the edit button should lead to a separate page where data can be modified. ...

jQuery slide adjusts the width of the slide as it transitions

The script is running smoothly. Check out the jsFiddle here The issue lies in its width adjustment when sliding (clicking "here"). It seems to be cutting off the width related to a 100px margin-left in #slider. Why does it seem to "jump" and how can this ...

The initialization of Firebase is not being completed before it is being called in other files

I am currently working on a vue project and I am attempting to integrate firebase. However, I have encountered an issue where my other JavaScript files like auth.js are utilizing firebase before it is properly initialized in my main.js file (which acts as ...

I keep encountering an attach() error every time I try to close a modal that contains a vee-validated form

Every time I try to close a bootstrap modal (using bootstrap-vue) that includes a vee-validated "update" form with vue.js, I encounter the following error: main.js:477686 Uncaught (in promise) Error: [vee-validate] Validating a non-existent field: "#35". ...

JavaScript validation for radio buttons that are grouped together

Need help with a JavaScript validation issue regarding grouped radio buttons named optionRadios1 to 5. I'm trying to validate them before submitting the form, but my code isn't working as expected and still allows the form submission. Below is t ...

The most efficient method for handling a vast amount of data in NodeJS

My database consists of 4 million numbers and I need to quickly check if a specific number exists in it. Example of the database: [177,219,245,309,348,436,...] I initially tried using a MySQL table for this task, but it took a lengthy 1300ms just to chec ...

Retrieving ViewBag Data following a successful $.ajax post in C# .NET Razor

When I use ajax to post data, it successfully goes through. However, when I try to retrieve the posted data from ViewBag on the controller side, I encounter an issue. Here's the Ajax Code: $.ajax({ type: "POST", url: '../Home/ ...

Set the display property of all child elements within the DIV to none

CSS <div class="container"> <span></span> <input type="text"> </div> JavaScript function hideElements(){ let container = document.querySelector(".container"); let elements = ...

Explore jQuery RSS search dropdown by value and text

I need assistance with a dropdown on my website, set up as follows: <select name="cboService" id="cboService" tabindex="10"> <option selected="selected" value="Novalue">Select Service</option> <option value="011">UPS Standard -- £ ...