Tuesday, 15 May 2012

javascript - position span element as appended to div -



javascript - position span element as appended to div -

i'm making little ascii ski free game... throwback win95 game.

for reason, appended obstacle spans beingness clumped 1 side, despite me setting position absolute , left random coordinate.

here's how should (spans randomly distributed):

here code snippet generates obstacles @ interval , assigns absolute positioning , left positioning:

function objectfactory() { var randobj = math.floor((math.random()*7)+1), randx = math.floor((math.random()*700)+1), randy = math.floor((math.random()*400)+1); $('#myobstacles').append("<span id=\"" + randx + "\">" + items[randobj] + "</span>"); document.getelementbyid(randx).style.position = "absolute"; document.getelementbyid(randx).style.left = randx; document.getelementbyid(randx).style.top = 500; console.log(document.getelementbyid(randx).style.left); }

the appended divs not beingness assigned left position:

here's how should look:

and, console.log(document.getelementbyid(randx).style.left); doesn't display anything.

any thoughts?

you need give units when assigning .style.left , .style.top:

document.getelementbyid(randx).style.left = randx + "px"; document.getelementbyid(randx).style.top = "500px";

(normally "or you're using jquery" followed illustration selector, id selectors starting digits pita...)

but separately: if 2 (or more) of randomly-created obstacles in same randx position? you'll end creating multiple elements same id, invalid.

instead, work straight objects:

function objectfactory() { var randobj = math.floor((math.random()*7)+1), randx = math.floor((math.random()*700)+1), randy = math.floor((math.random()*400)+1), obstacle = $("<span id=\"" + id + "\">" + items[randobj] + "</span>"); obstacle.css({ position: "absolute", left: randx, top: 500 }).appendto("#myobstacles"); }

side note: whenever find assigning static style info lot of elements (position: absolute, top: 500px), it's worth looking @ whether utilize class instead.

javascript jquery html css

No comments:

Post a Comment