noober
noober

Reputation: 4938

Proper deleting HTML DOM nodes

I'm trying to create a star shining animation.

function ShowStars()
{
    //if ($('img.star').length > 5)
    //  return;

    var x = Math.floor(Math.random() * gameAreaWidth) - 70;
    var y = Math.floor(Math.random() * gameAreaHeight);

    var star = document.createElement("img");
    star.setAttribute("class", "star");
    star.setAttribute("src", imagesPath + "star" + GetRandom(1, 3) + ".png");
    star.style.left = x + "px";
    star.style.top = y + "px";
    gameArea.appendChild(star);
    // Light.
    setTimeout(function () { star.setAttribute("class", "star shown"); }, 0);
    // Put out.
    setTimeout(function () { star.setAttribute("class", "star"); }, 2000);
    // Delete.
    setTimeout(function () { gameArea.removeChild(star); }, 4000);

    setTimeout(function () { ShowStars(); }, 500);
}

It works fine until I uncomment the following code which is supposed to regulate star count:

//if ($('img.star').length > 5)
//  return;

Then it stops to work as if the created stars are not removed (the first 5 stars blink then nothing happens). Why do the jQuery selector select them after gameArea.removeChild(star);? Isn't it enough to remove them from the parent node?

Browser: Google Chrome 17.

Regards,

Upvotes: 0

Views: 93

Answers (2)

Alohci
Alohci

Reputation: 82976

Change the commented out lines to

if ($('img.star').length > 5) {
  setTimeout(function () { ShowStars(); }, 500);
  return;
}

to keep the ShowStars recursion going.

Upvotes: 1

noober
noober

Reputation: 4938

I see a workaround: do not create stars dynamically, but insert them in HTML (<img id="star1">...<img id="starN">, where N is total count) then light and put out the existing nodes. Nevertheless, I'd like to understand, what's wrong with removing nodes in the question above.

Upvotes: 0

Related Questions