Adjust a CSS variable with a simple click

I have a challenge where I want to double the value of an element's property every time it is clicked, using CSS variables. Here's what I have tried:

#circle_1 {
      width:50px;
      height:50px;
      width: var(--size_1, 50px);
      height: var(--size_1, 50px);
  }
  

And also this:

// Variables
  var circle_1 = document.querySelector("#circle_1");
  var size_1 = document.getPropertyValue("--size_1");

  // Function to grow the circle
  function growCircle() {
      var size_1_n = size_1 * 2;
      circle_1.style.setProperty("--size_1", size_1_n.value);
  }

  // Event listener
  var el = document.getElementById("circle_1");
  el.addEventListener("click", growCircle, false);
  

You can view the code snippet here https://codepen.io/daiaiai/pen/QQXrGz

However, nothing seems to be happening when I click. I suspect there might be something wrong with `var size_1 = document.getPropertyValue("--size_1");`, but I'm unable to pinpoint the issue. Any guidance would be greatly appreciated!

Answer №1

Your codepen has several issues that need to be addressed for it to function correctly. I have made some adjustments and provided a working example instead.

Here are the key modifications I've made:

  1. I added a :root declaration for the variable, allowing me to access the value of --size_1 at the element circle_1. This prevents getting NaN as the value in case the variable is not declared elsewhere in the styles.

    You could use conditions to retrieve computed values for width or height, but I find it neater to set a default value in :root.

  2. As you're setting the value with units like 50px rather than just 50, extracting the numerical part is necessary before doubling it. I achieved this using parseInt(size_1).

var circle_1 = document.querySelector("#circle_1");
var size_1 = document.body.style.getPropertyValue("--size_1");

// Function to enlarge the circle
function growCircle() {
  var size_1 = window.getComputedStyle(circle_1).getPropertyValue("--size_1");
  var size_1_n = parseInt(size_1) * 2;
  circle_1.style.setProperty("--size_1", size_1_n + "px");
}


// Event listener
circle_1.addEventListener("click", growCircle, false);
:root {
  --size_1: 50px;
}

body {
  margin: 100px;
}

#circle_1 {
  width: var(--size_1, 50px);
  height: var(--size_1, 50px);
  border-radius: 50%;
  margin-top: 20px;
  background-color: pink;
  opacity: 0.7;
  display: inline-block;
  transition: 0.3s;
}

div span {
  position: relative;
  top: 50%;
  left: 50%;
  text-align: center;
}
<div id="circle_1" draggable="true"><span>Group 1<span></div>


An alternative approach would be defining only the value component in the variable's :root declaration. You can then reference its value using width: calc(var(--size_1) * 1px).

In my opinion, this method is cleaner as the variable holds just the value part, enabling you to apply any unit during style declaration. It also eliminates the need for parsing the variable's value.

Below is the code snippet reflecting this approach:

var circle_1 = document.querySelector("#circle_1");
var size_1 = document.body.style.getPropertyValue("--size_1");

// Function to grow the circle
function growCircle() {
  var size_1 = window.getComputedStyle(circle_1).getPropertyValue("--size_1");
  var size_1_n = size_1 * 2;
  circle_1.style.setProperty("--size_1", size_1_n);
}


// Event listener
circle_1.addEventListener("click", growCircle, false);
:root {
  --size_1: 50;
}

body {
  margin: 100px;
}

#circle_1 {
  width: calc(var(--size_1, 50px) * 1px);
  height: calc(var(--size_1, 50px) * 1px);
  border-radius: 50%;
  margin-top: 20px;
  background-color: pink;
  opacity: 0.7;
  display: inline-block;
  transition: 0.3s;
}

div span {
  position: relative;
  top: 50%;
  left: 50%;
  text-align: center;
}
<div id="circle_1" draggable="true"><span>Group 1<span></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

Express error handling lacking clarity

My application has a route dedicated to accepting file uploads: Here's a snippet from app.js ... var upload = require('./routes/upload'); ... app.use('/upload', upload); ... ... /* It is essential to start the application with ...

Move the DIV element to the bottom of the webpage

On my website, I have implemented a countdown timer and a responsive wallpaper. My goal now is to center the div at the bottom of the page and make sure it always stays there. I've tried some code snippets from StackOverflow, but they either gave me a ...

The proper invocation of the success and error functions in jQuery is not being achieved for Ajax calls

After successfully sending JSON data to a specified URL using Postman and receiving the required response in JSON format, I intended to send this JSON data to another file by utilizing AJAX post method. However, to my dismay, the Ajax post method failed to ...

React component refuses to re-render

I am facing an issue with my menu re-rendering in React. The handleToggleFunction only works for the first click, after which nothing happens and the state does not update. I am using Tailwind CSS in this component. Here is my code: I have attempted to us ...

Utilizing JSON information acquired through AJAX within a distinct function

Sorry if this question has been asked before, I tried following suggestions from another post but they didn't work for me. What I'm trying to do is fetch some JSON data, save a part of it in a variable, and then use that variable in a different f ...

When attempting to input a value in the middle of the line, the cursor unexpectedly leaps to the end

I have successfully created a code that prevents spaces at the beginning and special characters in an input field. The code is working perfectly, but there is an issue with the cursor moving to the end when trying to type at the beginning or middle of the ...

Troubleshooting a scope problem with ng-include while maintaining the original template

I have a select box within my template that has the following structure: <form name="myForm" class="fixed-select"> <select name="repeatSelect" id="repeatSelect" ng-model="selectedItem"> <option ng-repeat="program in pro ...

Disabling padding on TwitterTweetEmbed component in React Twitter Embed

Having an issue with Material UI and React Twitter Embed, unable to remove top and bottom margins. Here's the code snippet causing concern: const styles = theme => ({ listItem: { padding: '0px', }, tweetSize: { margin: 0, ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Implementing conditional button visibility in Angular based on user authorization levels

I've been experimenting with the following code snippet: <button ng-if="!isAuthenticated()" ng-click="deleteReview()">Delete</button> In my JavaScript, I have: $scope.isAuthenticated = function() { $http.get("api/user ...

Error: Appwrite Login Authentication failed due to account.createEmailSession function not recognized as a valid function

Looking for help with Vue and Appwrite? Check out this tutorial: https://appwrite.io/docs/tutorials/vue/step-1 src/appwrite/index.js import { Client, Databases, Account } from "appwrite"; const client = new Client(); client .setEndpoint(" ...

Bootstraps paves the way for the destruction of a dropdown element

https://getbootstrap.com/docs/4.0/components/dropdowns/ $().dropdown('dispose') Erases the dropdown functionality of an element. What exactly does this mean? Does it remove the tag entirely? Does it render the tag unusable as a dropdown lis ...

Creating a LazyLoad setup with a scrolling DIV by utilizing the Intersection Observer API

I am currently utilizing the LazyLoad library from github.com/tuupola/lazyload and it works wonderfully when detecting images within the viewport of the body element. However, my challenge lies in having a fixed width and height DIV that covers the entire ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Creating a JavaScript function that responds to multiple click events

Can someone please help me out? I have the link to the output of my work below using JavaScript and HTML: My goal is for only one circle to be active when clicked, while the others are disabled. Currently, when I click on a circle and then another one, bo ...

Troubleshooting problem with media queries in CSS

As a newbie to HTML and CSS, I've been encountering difficulties with media queries. My website seems to only function properly when viewed in a resolution of 1920x1080, so I attempted to implement some media queries in my CSS to cater to other resolu ...

Tips for updating a plugin from phonegap 2.5 to the most recent version 3.1, and the steps to follow when including a new plugin in phonegap

$('#sendSms').click(function(e){ alert("Sending SMS in progress");//After this alert, I encountered continuous errors and couldn't determine the root cause var smsInboxPlugin = cordova.require('cordova/plugin/smsinboxplugin'); ...

Passing props in Vue router results in the props being undefined

I am attempting to pass a props via the vue router using a router link that appears like this <router-link :to="{ name: 'product-details', params: { productId: 123 } }" class="product-sbb d-block"> Below are my routes { ...

Tips on minimizing the vertical size of a mat field housing a mat-select dropdown

I need help reducing the height of a mat field that includes a mat-select in Angular v15. The code is directly from the material components documentation, with no alterations. It consists of a default table and default outline formfield. <mat-form-fi ...

The battle between Typography and HTML formatting elements

When it comes to choosing between the <Typography/> tag and normal HTML tags like <p>, I find myself in a state of ambiguity. <Box className={someClassName}> <Typography>{someVariableName}</Typography> </Box> or <p ...