The 'css' property cannot be set on something that is undefined

I'm attempting to dynamically change the size and color of a circle based on user input in the form fields. However, I've encountered the following error:

Cannot set properties of undefined (setting 'css')

Could anyone provide guidance on how I can resolve this issue?

window.addEventListener("DOMContentLoaded", (event) => {
  const inputsize = document.getElementById("size");
  const inputcolor = document.getElementById("color");
  const circle = document.getElementsByClassName("circle");

  let size = 100;
  let color = "#b66465";

  window.onchange = (event) => {
    let myStyles = "height: " + size + "px; width: " + size + "px; background-color: " + color + ";";
    circle.style.css = myStyles;
  };

  inputcolor.onchange = (event) => {
    color = inputcolor.value;
    let myStyles = "height: " + size + "px; width: " + size + "px; background-color: " + color + ";";
    circle.style.css = myStyles;
  };

  inputsize.onkeyup = (event) => {
    size = inputsize.value;
    let myStyles = "height: " + size + "px; width: " + size + "px; background-color: " + color + ";";
    circle.style.css = myStyles;
  };
});

Answer №1

The key problem with your code is that the Element.style does not have a css property. It is best practice to set the individual style properties separately, corresponding to CSS properties, instead of as a single CSS string.

Moreover, getElementsByClassName() returns a collection of Element objects, so you cannot directly access the style property on it. If there are multiple .circle elements in the DOM, you will need to iterate through them.

It is also recommended to use addEventListener() over using onclick or other onX properties.

Here is a revised example that addresses these issues:

window.addEventListener("DOMContentLoaded", () => {
  const inputSize = document.querySelector("#size");
  const inputColor = document.querySelector("#color");
  const circles = document.querySelectorAll(".circle");
  
  const updateCircles = () => {
    circles.forEach(circle => {
      circle.style.width = inputSize.value + 'px';
      circle.style.height = inputSize.value + 'px';
      circle.style.backgroundColor = inputColor.value;
    });
  }

  inputColor.addEventListener('input', updateCircles);
  inputSize.addEventListener('input', updateCircles);
});
label {
  display: block;
}
.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #000;
  margin: 20px;
  display: inline-block;
}
<label>
   Size:
   <input type="number" id="size" value="100" />
</label>
<label>
   Color:
   <input type="color" id="color" value="#000000" />
</label>

<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></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

Creating a jQuery multiple image preview feature is a simple and effective way to

Looking to implement a single image upload preview function in jQuery? Want to modify it to allow for multiple image uploads with separate boxes? Check out the HTML script below. <!DOCTYPE html> <html> <head> <title></title> ...

Tips for halting a MySQL database transaction within a NodeJS environment using expressJS

Recently, I encountered a coding challenge that involved managing a long database transaction initiated by a user. The scenario was such that the user inadvertently updated 20 million entries instead of the intended 2 million, causing a significant impact ...

Preserve object properties while allowing for changes to be made without affecting

I am in need of transferring specific properties from one object to another while ensuring that the original object remains mutable. Here is the original object: var sourceObject = { "key1": "value1", "key2": "value2 ...

Introducing React JSX via a nifty bookmarklet

Looking to convert code found in an HTML file into a bookmarklet? Here's the code snippets involved: <script src="JSXTransformer-0.13.3.js"></script> <script src="react-0.13.3.js"></script> <script type="text/jsx;harmony=tr ...

Switch between two fields using just one animation

I've been experimenting with creating an information tag that slides out from behind a circular picture. To achieve this effect, I created a block and circle to serve as the information field placed behind the image. However, I'm facing a challe ...

The Vue router is unable to access the store state

My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the ...

Error: The specified module could not be found: Could not resolve 'react-hot-loader/webpack'

After constructing my React project, I encountered the error shown below. How can I resolve this issue? I am utilizing the latest version of react-hot-loader. I have attached a screenshot of the error here ...

Requesting information from a model using a JavaScript variable in a cshtml file in an ASP.NET application

Is there a way to use a JavaScript variable to retrieve a specific item from an array stored in a model? Below is a code snippet: function CreateCategoryList() { var limit = @(Model.CategoriesCount.ToString()); for (i=0; i<limit; ...

What is the best way to position a title and subheading alongside an image?

I am currently working on developing a blog using php and html to enhance my coding skills. On my website, I have a special category where I display posts, the number of which can vary. Each post is composed of a title, a subheading, and a placeholder div ...

Learning the ins and outs of HTML5 and CSS3

Does anyone have recommendations for high-quality HTML5 and CSS3 tutorials? ...

Strong tags within MFC

Is it possible to create labels in MFC (Static text) that contain both bold and non-bold text? For instance, something like this: "I want my label to have a mix of styles like this" Any suggestions on how to achieve this? I am aware that I can change ...

Get Code Now Button

I operate a website dedicated to Amazon reviews, and I am in need of a button that can request a code from a text file uploaded by the seller. My question is how can this be achieved using HTML? I have been experimenting with this sample: <!-- Butt ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

Eliminate disparity in Woocommerce shopping cart

I have a pizza with various toppings. When the user selects "Add Toppings," they appear as drop-down options defaulted to "none." I want to hide the selected "none" options in the cart and checkout. Although I've successfully hidden them on the cart ...

How can you apply margin to an element within a column in Bootstrap 4?

Within a column, I have several span elements: <div class="container-fluid"> <div class="row"> <div class="col"> <span class="myClass">some text</span> <span class="myClass">some text</span> ...

Throttle the RxJs interval based on the inner observables

Sorry if the way I am asking this question is not clear, I am having difficulty finding the right words to explain it. I am currently working on Selenium automation and here is how the process goes:- Go to a specific page Every 1 second, check if the pag ...

Verify the status of the nested reactive forms to determine if the child form is in a dirty state

I am working on a form that consists of multiple sections within nested form groups. I need to find a way to detect when changes are made in a specific section. Here is the HTML structure: <div [formGroup]="formGroup"> <div formGroupN ...

What are some ways to style an image that has been added using JavaScript using CSS?

I utilized a JavaScript function to add an image, which looked like this: function show_image(src) { var img = document.createElement("img"); img.src= src; document.body.appendChild(img); } But when I attempt to change its style using CSS: img ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

Switch Background Image - The image failed to display

Here is the code snippet I am currently working with. It involves displaying a background-image when clicking on a link with the class 'home-link', and not showing an image if the link does not have this class. The issue at hand: The problem ari ...