I am trying to learn Javascript and integrate it into a webpage however when trying to use a JavaScript random function that changes the size of a line on click nothing happens?
function randomnumber(min, max) {
var rn = Math.random() * (max - min) min;
document.getElementById("rain").style.width = rn;
}
body {
background:#000000;
}
.line {
height: 1px;
width: 40px;
background: white;
transform: rotate(45deg);
}
<div id="rain" onclick="randomnumber(1px,100px)">
<div >
<div ></div>
</div>
</div>
CodePudding user response:
You cannot use as a parameter of a javascript function a css value such as 100px or something like 1rem.
In the 'rain' div use this code:
//...
<div id="rain" onclick="randomnumber(1, 100)">
//...
</div>
//...
CodePudding user response:
- The parameters in your function have to be integers to apply arithmetics on it.
- If you are setting a width you have to add the unit like
px. - In your CSS you are setting the width of the element having the class
line, but in your JS your are changing the value of the element having the classrain- to change the width you've set in css you can use thequerySelectorprovided below.
function randomnumber(min, max) {
var rn = Math.random() * (max - min) min;
document.querySelector('#rain .line').style.width = rn 'px';
}
body {
background:#000000;
margin: 100px;
}
.line {
height: 5px;
width: 50px;
background: white;
transform: rotate(45deg);
}
<div id="rain" onclick="randomnumber(1,100)">
<div >
<div >
</div>
</div>
</div>
CodePudding user response:
The problem is you consider the 1px and 100px to be number, but the type of 1px and 100px is string. Also, you can't use 1px and 100px to do Math.
Also, another problem make your code won't work is your are trying to assign the width to parent element of line (the rain) and since rain doesn't have any style, it won't work as well. You should directly apply style for line
function randomnumber(min, max) {
var rn = Math.random() * (max - min) min;
document.querySelector(".line").style.width = rn 'px';
}
body {
background:#000000;
}
.line {
height: 1px;
width: 40px;
background: white;
transform: rotate(45deg);
}
<div id=rain onclick="randomnumber('1','100')" >
<div >
<div >
</div>
</div>
</div>
