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 class="size">
<div class="line"></div>
</div>
</div>
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 class="size">
<div class="line">
</div>
</div>
</div>
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>
//...
px.line, but in your JS your are changing the value of the element having the id rain - to change the width you've set in css you can use the querySelector provided 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 class="size">
<div class="line">
</div>
</div>
</div>