Yogzzz
Yogzzz

Reputation: 2785

JavaScript absolute position of element on images

I have created a new div and adding it to all images on the page as follows:

var images = document.getElementsByTagName('img');
        for (var i = 0; i < images.length; i++) {    
var divLink = document.createElement("div");
    divLink.style.position = "absolute"; divLink.style.top = "10px"; divLink.style.right = "10px"; divLink.style.zIndex="1"; divLink.style.fontSize = "20px"; divLink.style.backgroundColor = "black"; divLink.style.color = 'white';
    divLink.innerHTML = linkCount;
    images[i].parentNode.insertBefore(divLink, images[i] );
}

This is working well for all images except images contained in a <ul>. For these images, each divLink is moved to the right of the <ul> and stacked on top of one another. If I remove the divLink.style.right = "10px"; the divLink moves by default to the left of the image.

How can I position the divLink to the top-right corner of the image, for all images including those in the <ul>.

Upvotes: 0

Views: 3534

Answers (3)

Janak
Janak

Reputation: 5052

If you add poistion:absolute and mention top/left/right/bottom , the elements tends to stack on each other .

There are 2 ways to do this :

1> Do not assign any position.Let it remain "STATIC". Move the "images" using the margin properties.

Eg:

 divLink.style.margin-top = "10px";
 divLink.style.margin-right= "10px";
        OR

2> Make just the position:absolute without mentioning top/left/right/bottom properties, this way they will not stack on each other. Unless you don't want to move the "images" explicitly using top/left, that is of no use.

Upvotes: 0

SadhanaP
SadhanaP

Reputation: 37

There seems no need to give position:absolute to the images. You can simply append the images without giving the position attribute and move the images using the margin property.

  divLink.style.margin-top = "10px";
  divLink.style.margin-right= "10px";

Upvotes: 0

Ilya
Ilya

Reputation: 29693

Use relative position instead of absolute

divLink.style.position = "relative";  

Upvotes: 2

Related Questions