Hagbart Celine
Hagbart Celine

Reputation: 470

Getting the right position of an IMG and calculating the distance to right side of screen

I have been trying to find a solution to a problem I have.

My website has different thumbnails on it and I added a onmouseover / onmouseout function. So if you move your mouse over a picture, a hover image (the original size) is shown in the upper right corner.

This all works fine, but if I have bigger image, it will overlap my thumb img and stuff gets crazy.

So what I wanted was to get the right side position of my thumbnail IMG tag and subtract that from the screen size. The screen size is not a problem, but the right position of my img tag is.

How could i get that position? (marked with bold red line in pic)

position of thumbnail img

The code looks something like this:

function imghover(id, src, width, height) {
        var thumb = document.getElementById(id);
        var hover = document.getElementById('hoverimg');
        alert(thumb.
        hover.src = src;
        if(width > screen.width){
            hover.width = (width / 100) * 20;
            hover.height =  (height/ 100) * 20;
        }
        else if(height > screen.height) {
            hover.width = (width / 100) * 40;
            hover.height =  (height/ 100) * 40;
        }
        else {
            hover.width = width;
            hover.height =  height;
        }
    
}

As you can see i have everything I need: Thumb ID, scr for new pic (original), width & height of original. So how to get the right side position of the Thumb?

Thanks a lot in advance.

Upvotes: 0

Views: 292

Answers (2)

Mayank Tripathi
Mayank Tripathi

Reputation: 1352

Here is the code for your problem: http://jsfiddle.net/B24QL/

You can view the preview here : http://jsfiddle.net/B24QL/embedded/result/

jQuery

$(document).ready(function(){
var a = $('img').offset().left + $('img').width(),
    b = $(window).width() - a;
alert("Position of right border of image: " + a + "px from left edge.\n Distance between right border and image = " + b + "px.");
});

Upvotes: 0

TwiToiT
TwiToiT

Reputation: 1201

right is usually calculated as

right = totalScreenWidth - left - sizeOfBox(or what ever detail you wand to + -);

The equation is followed in a relative way .. say for example the whole thing is in a div container rather than in window.

You can get left for image like ..

totalLeft = image.getBoundingClientRect().left + imageParent.getBoundingClientRect().left + .... cascadingly .. till you cover each element from image to window.

or use jquery to use it like $(#img).position().left .. etc

Upvotes: 1

Related Questions