I am trying to change the circle size when entering a value in the input, and trying to change the color. But I am getting the following error:
Cannot set properties of undefined (setting 'css')
Can any of you be helpfull with what i can do?
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;
};
});
CodePudding user response:
The main issue in your code is because Element.style
has no css
property. It's intended that you set the individual style properties, which generally map to CSS properties, one by one, not as an entire string of CSS.
In addition, getElementsByClassName()
returns a collection of Element objects, so you can't call style
on it directly. If you have multiple .circle
element in the DOM, you would need to loop through them.
Also note that it's better practice to use addEventListner()
instead of onclick
or other onX
properties.
Below is a working example with these issues addressed.
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 ></div>
<div ></div>
<div ></div>
CodePudding user response:
Change circle.style.css
circle.style.css = myStyles;
to it
circle.style.cssText = myStyles;