Martin Smellworse
Martin Smellworse

Reputation: 1762

Position images exactly using javascript

I need to create dozens of small images and position them absolutely on the screen relative to the top and left of the screen. I have a page with one div on it and, at the moment, I am experimenting with creating each element using javascript. How can I position each element precisely?

var divo = document.getElementById('pagediv');
var objImage = document.createElement('img');
objImage.setAttribute('src', 'images/Red_L.gif');
divo.appendChild(objImage);

That is creating the image okay and putting it on the screen. But how can you tell it exactly where to be positioned?

Upvotes: 1

Views: 254

Answers (4)

Foreign Object
Foreign Object

Reputation: 1640

Using offsetTop and offsetLeft could potentially solve your problem http://www.quirksmode.org/js/findpos.html — but it can be buggy in some browsers. I would suggest employing getBoundingClientRect http://ejohn.org/blog/getboundingclientrect-is-awesome/ to get and offset each images x/y coordinate.

Upvotes: 0

Harsha Venkataramu
Harsha Venkataramu

Reputation: 2914

If you are creating the images dynamically,I believe you could could run it through a loop and position the images.

    var divo = document.getElementById('pagediv');
    var leftPos = 0;
    var newSrc = '';
    for(i = 0 ; i < 12 ; i++)
    {
        newSrc = "images/red_"+i+".png";
        var objImage = document.createElement('img');
        objImage.src = newSrc;
        objImage.style.left=leftPos+20+"px";
        objImage.style.zIndex=2;
        objImage.style.position="absolute";
        leftPos = objImage.style.width;
        divo.appendChild(objImage);
    }

If your images are named red_1.png,red_2.png and so on,this code will position the images one next to another with a spacing of 20px in between each other.

Upvotes: 1

epascarello
epascarello

Reputation: 207557

"At specific x/y coordinates"

Set the CSS for it.

var divo = document.getElementById('pagediv');
var objImage = document.createElement('img');
objImage.setAttribute('src', 'images/Red_L.gif');
objImage.style.top="100px";
objImage.style.left="100px";
objImage.style.zIndex=2;
objImage.style.position="absolute";
divo.appendChild(objImage);

Upvotes: 0

juanignaciosl
juanignaciosl

Reputation: 3573

I suppose you should take a look at CSS absolute positioning.

Upvotes: 0

Related Questions