The Jquery css function does not support the setting of CSS3 variables

Hello there,

I'm currently experimenting with CSS3 variables to adjust elements and various other things dynamically, but I've run into an issue where JQuery's css method seems to ignore any attempt to set a CSS variable. Here is what I've tried:

$(document).ready(function() {
            $('#testdiv').css('--bgc','rgb(0,0,255)');
        });
 div {
            --bgc: rgb(255, 0, 0);
            background-color: var(--bgc);
            width: 50px;
            height: 50px;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="testdiv"></div>

According to the setup, the div should initially display as a 50px by 50px red box, and once the page has finished loading, it should change to a blue box. However, the --bgc variable on the DIV remains unchanged. Is there a way to achieve this using JQuery?

Answer №1

Look at this awesome solution I discovered using only pure JavaScript:

JavaScript:

$(document).ready(function() {
    document.documentElement.style.setProperty('--bgc', 'rgb(0,0,255)');
});

CSS:

:root {
    --bgc: rgb(255,0,0);
}

div {
    background-color: var(--bgc);
    width: 50px;
    height: 50px;
}

Check it out on Codepen: http://codepen.io/theblindprophet/pen/yJpZNb

For more information, visit: Variables why should you care?

Answer №2

You have the ability to assign variables using plain JavaScript

$(document).ready(function() {
  $('#testdiv')[0].style.setProperty('--bgc', 'rgb(0, 0,255)');
});

$(document).ready(function() {
  $('#testdiv')[0].style.setProperty('--bgc', 'rgb(0,0,255)');
});
div
{
    --bgc:rgb(255,0,0);
    background-color:var(--bgc);
    width:50px;
    height:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testdiv"></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

Element positioning in Material UI is fluid and responsive across all devices, with the ability to place elements at

As a novice in layout design, I am currently developing a web application for both mobile and desktop using React and Material UI. My challenge lies in placing the app navigation at the bottom of the screen. The issue arises because the location of the app ...

Error occurred during the parsing of an AJAX response

Hello, I am currently exploring the world of JavaScript and jQuery. I recently encountered a situation where I initiated an AJAX call in my code and received an unexpected response. https://i.sstatic.net/AUHb7.png My current challenge revolves around imp ...

Steps for building an HTML tree

Exploring HTML files can be daunting, especially for someone with limited experience in this field. I am seeking assistance to transform these files into a more readable format, represented as a tree structure with each tag on a separate line. However, des ...

Eliminate Video Time Indicator

Can the video progress bar be removed from this specific video player? I would like it to be integrated into the embed code that I share with others. <iframe id="hapyak-player-157199-8825" marginwidth="0" marginheight="0" frameborder="no" scrolling=" ...

How is it possible for a JavaScript variable sharing the same name as a div Id to automatically pass the div?

This is just ridiculous. Provided HTML <p id = "sampleText"></p> Javascript var sampleText = "Hello World!"; Execution console.log(sampleText); // prints <p id = "sampleText"></p> How is this even possible? I ...

Struggling to get the duplication validation to function properly using Ajax in a Rails application

I am attempting to use AJAX to call a method that checks for duplicate emails. Here is the code I have so far: #users_controller.rb def check_email email = User.find_by(email: params[:email]) #record exists if email render :json => { status: " ...

Retrieve the date earlier than the present date using a datepicker

I am using a datepicker that automatically loads with the current date. However, I am facing an issue where I need to determine if the date selected by the user is before the current date and display a message accordingly. Can anyone help me with a solut ...

Crashing of history.pushState when using browser's back button

I am currently developing a single page application that loads each section via ajax. The homepage is a separate page, and when you click on 'About', it redirects you to the single page app. I have been able to update the URL for each section and ...

HTML Changing the background color of the body using HTML elements

I need assistance with an exercise that requires changing the color of a letter and background when clicking on text. I have successfully changed the text color but am struggling to change the background color. Can someone provide guidance? <html> ...

Discovering the process of searching for options in a dropdown menu

I'm currently implementing select2min.js for a dropdown select box. Currently, it's functioning well for a single drop-down: <select> <option>abc</option> </select> It works fine with the following code: $("#myId0"). ...

Update the Navbar links to smoothly slide along the navigation bar as the width decreases, instead of awkwardly

When in full screen, the Navbar links are displayed horizontally. https://i.stack.imgur.com/0mOLp.png However, when the width changes, they appear like this https://i.stack.imgur.com/2ylgZ.png Is there a way to ensure they shift to the left while maint ...

Setting the default value of an input in Angular 2 or higher

I am currently working on incorporating a Component that mirrors a Bootstrap modal with an input field. The input is linked to a variable in the Component class using [(ngModel)]="...". It functions properly when I type text into the input (the variable&ap ...

"Use jQuery to change the value on click to 22

I am facing an issue with my code that is supposed to change the anchor and id values when clicked. Although the value and anchor do change, it only works once. Can anyone help me understand why it's not working? HTML <a href="#" id="enable-edit-b ...

Tips for keeping an image at a fixed size within a grid, even when the browser window is resized

As a newcomer to front end coding, I am currently working on a practice website to familiarize myself with the code. One issue I am facing is related to using a bootstrap grid with an image in the left column. I want to prevent the image size and position ...

Encountering problem when trying to upload several images at once using a single input in CodeIgniter with

I'm attempting to use CodeIgniter and AJAX to upload multiple images using a single input field. Here's the code I have so far: HTML: <input type="file" name="files[]" id="file" multiple /> AJAX: $("#addItems").on("submit",function(e) { ...

Preventing arrow keys from activating buttons

Currently, I am working on a program that involves moving an image on a form using arrow keys. Initially, everything was functioning as expected - the image would move in response to pressing the arrow keys. However, upon adding a button to the form, I enc ...

Changing $scope does not automatically refresh the selected option when using ng-options with <select> in AngularJS

My select element is structured like this: <select ng-model="exportParam" ng-options="item as item.lib for item in allExportParams | orderBy:'lib'" class="form-control"> </select> To save its state for later display, I sto ...

Alter the appearance of a webpage dynamically based on the size of the browser window using jQuery or JavaScript

Hey everyone, I've been silently observing for a while now and I'm hoping someone can assist me with a project. I want to create a responsive "3D" cube that flips when hovered over. I've got the cube design nailed down after finding inspira ...

Code-behind not functioning properly for Bootstrap Modal

Whenever the password or username are incorrect, I need to open a modal and keep it in the 'Else' statement. However, it is not working, the modal does not open. protected void bntLogar_Click(object sender, EventArgs e) { Registrar c ...

I'm currently facing an issue with toggling the visibility of a div using JavaScript

In my attempt to create a unique custom select menu using html, css, and javascript, I encountered an issue with toggling the display style of the div containing the options when clicking on the button (in this case, an arrow). HTML: <ul class="de ...