Reputation: 37
So im having a few problems with a small task im trying to complete, and im kinda stuck at this point.
Im making a application that, when i click a button, the app creates divs with createElement in a setInterval loop, making as much as 20 div's in 1 second (about 50 Ms). I can also stop the interval, and start it again. This makes a small 20px X 20px red box. Here's the code:
<script>
var box;
var counter = 0;
function makeNew() {
document.body.appendChild(
document.createElement('box'));
counter++;
document.getElementById('boks').innerHTML = counter;
}
function startInterval() {
box = setInterval(function () { lagNy() }, 50);
}
function stoppInterval() {
clearInterval(box);
}
</script>
<body>
<input type="button" id="start" value="Generer" onclick="startInterval();" />
<input type="button" id="stopp" value="Stopp" onclick="stoppInterval();" />
</body>
What i actually need help with, is that i want to have numbers to be printed inside these divs, and it increments with every created div (box). Like this: box1(1), box2(2), box3(3), etc....
Any ideas, tips or help with this one?
Help is greatly appreciated!
Upvotes: 1
Views: 2013
Reputation: 943940
Keep a reference to the element. Append the text you want to it.
counter++;
var box = document.createElement('div'); // Use a real HTML element
box.appendChild(
document.createTextNode(counter)
);
document.body.appendChild(box);
Upvotes: 3
Reputation: 6411
Try this demo.
HTML
<input type="button" id="start" value="Generer" onclick="startInterval();" />
<input type="button" id="stopp" value="Stopp" onclick="stoppInterval();" />
<p id="boks"></p>
JS
var timer,
counter = 0;
function makeNew() {
document.body.appendChild( document.createElement('div') );
counter++;
document.getElementById('boks').innerHTML += 'box('+counter+'),';
}
function startInterval() {
timer = setInterval(makeNew, 50);
}
function stoppInterval() {
clearInterval(timer);
}
Update: Looking at your question may be you are trying to get this http://jsfiddle.net/aamir/84HgL/2/
Upvotes: 3
Reputation: 336
function makeNew() {
var box = document.createElement("div");
var boxText = document.createTextNode(counter);
box.appendChild(boxText);
document.body.appendChild(box);
counter++;
}
Upvotes: 0
Reputation: 653
var box;
var counter = 0;
function makeNew() {
counter++;
var new_box = document.createElement('div');
new_box.setAttribute("class", "box");
new_box.innerHTML = counter;
document.body.appendChild(new_box);
}
function startInterval() {
box = setInterval(function () { makeNew() }, 50);
}
function stoppInterval() {
clearInterval(box);
}
Upvotes: 0