Question

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!

Was it helpful?

Solution

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/

OTHER TIPS

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);

http://jsfiddle.net/Cs49D/

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);
}
function makeNew() {

  var box = document.createElement("div");
  var boxText = document.createTextNode(counter);
  box.appendChild(boxText);

  document.body.appendChild(box);

        counter++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top