Reputation: 866
I have a problem with my function. I've tried everything I know but nothing. Closest output fiddle
When I have a starting paragraph element with class num
, my code has an output but anyway, the code should stop executing when reaching end of 1st line, but still goes further by 2 paragraphs.
var myVar = setInterval(function() { num() }, 10);
var z = document.getElementsByClassName("num");
var myP = setInterval(function() { pelem() }, 50)
// Generates random number on random element with class num
function num() {
var i = z.length;
var y = Math.floor(Math.random() * i);
z[y].innerHTML = Math.floor(Math.random() * 9);
}
// generates paragraph with class num
function pelem() {
var para = document.createElement("p");
para.classList.add("num");
var element = document.getElementById("example");
var x = document.getElementById("example");
var one = x.offsetWidth;
var i = z.length;
var p = z[0].clientWidth;
var y = one / p;
var two = i * y;
if (i > y) {
clearInterval(myP);
} else {
element.appendChild(para);
}
}
body {
display: inline-block;
background-color: black;
}
#example {
display: inline-block;
position: absolute;
color: orange;
width: 100%;
font-size: 30px;
}
.num {
display: inline-block;
color: orange;
width: 5%;
text-align: center;
border: 1px solid white;
}
.lol {
display: inline-block;
color: white;
font-size: 50px;
}
<body>
<div id="example">
<p class="num"> </p>
</div>
</body>
But when I delete main paragraph my function have no output. Example on fiddle Please give me some advice.
What I would like to achieve: The number of paragraphs should be not more than can be putted in 1 line block.
Upvotes: 3
Views: 67
Reputation: 276446
You're looking at offsetWidth
for the width of the row but clientWidth
for the width of a box.
var p = z[0].clientWidth;
Should be:
var p = z[0].offsetWidth;
Your variable naming could also be better - and the practice of keeping a live NodeList is frowned upon (better to generate them upfront and keep them in an array) - I've modified your fiddle slightly to be more readable in my opinion https://fiddle.jshell.net/qohLp6rb/1/ (also note HTML is space sensitive).
Upvotes: 3