PeterJ
PeterJ

Reputation: 21

How do I calculate an elements position in a scrolled div?

I have a div with absolute positioning set to allow vertical scrolling. My app includes drag & drop facilities that rely on me determining the coordinates of elements when events are fired.

The offsets I use to calculate elements positions (i.e. element.offsetLeft & element.offsetTop) only relate to original position of the element and do not account for changes in position that result from the user having scrolled. I figured I could add in a correction if I could calculate the distance scrolled but I can't see any way to do that (unlike with window scrolling).

Would really appreciate any suggestions.

Upvotes: 2

Views: 10022

Answers (3)

djorgenson
djorgenson

Reputation: 11

Here's a cross-browser solution that finds an element's position taking into account scrolling div/s and window scroll:

var isIE = navigator.appName.indexOf('Microsoft Internet Explorer') != -1;

function findElementPosition(_el){
    var curleft = 0;
    var curtop = 0;
    var curtopscroll = 0;
    var curleftscroll = 0;

    if (_el.offsetParent){
        curleft = _el.offsetLeft;
        curtop = _el.offsetTop;

        /* get element scroll position */
        var elScroll = _el;
        while (elScroll = elScroll.parentNode) {
            curtopscroll = elScroll.scrollTop ? elScroll.scrollTop : 0;
            curleftscroll = elScroll.scrollLeft ? elScroll.scrollLeft : 0;

            curleft -= curleftscroll;
            curtop -= curtopscroll;
        }

        /* get element offset postion */
        while (_el = _el.offsetParent) {
            curleft += _el.offsetLeft;
            curtop += _el.offsetTop;
        }
    }

    /* get window scroll position */
    var offsetX = isIE ? document.body.scrollLeft : window.pageXOffset;
    var offsetY = isIE ? document.body.scrollTop : window.pageYOffset;

    return [curtop + offsetY,curleft + offsetX];
}

Upvotes: 1

PeterJ
PeterJ

Reputation: 21

This is what I'm implementing as a correction in case anyone's interested.

Thanks guys.

/*
    Find a html element's position.
    Adapted from Peter-Paul Koch of QuirksMode at   http://www.quirksmode.org/js/findpos.html
*/
function findPos(obj)
{
    var curleft = 0;
    var curtop = 0;
    var curxscroll = 0;
    var curyscroll =0;

    while(obj && obj.offsetParent)
    {
        curyscroll = obj.offsetParent.scrollTop || 0;
        curxscroll = obj.offsetParent.scrollLeft || 0;
        curleft += obj.offsetLeft - curxscroll;
        curtop += obj.offsetTop - curyscroll;
        obj = obj.offsetParent;
    }

    return [curleft,curtop];
}

Upvotes: 0

MyItchyChin
MyItchyChin

Reputation: 14031

Take a look at the scrollTop and scrollLeft properties of the div container.

Upvotes: 3

Related Questions