Waleed Eissa
Waleed Eissa

Reputation: 10513

How to get an element's top position relative to the browser's viewport?

I want to get the position of an element relative to the browser's viewport (the viewport in which the page is displayed, not the whole page). How can this be done in JavaScript?

Many thanks

Upvotes: 273

Views: 383795

Answers (13)

Johansrk
Johansrk

Reputation: 5250

Here is something for Angular2 +. Tested on version 13

event.srcElement.getBoundingClientRect().top;

Upvotes: 3

Maciej Kravchyk
Maciej Kravchyk

Reputation: 16607

Based on Derek's answer.

/**
 * Gets element's x position relative to the visible viewport.
 */
function getAbsoluteOffsetLeft(el) {
  let offset = 0;
  let currentElement = el;

  while (currentElement !== null) {
    offset += currentElement.offsetLeft;
    offset -= currentElement.scrollLeft;
    currentElement = currentElement.offsetParent;
  }

  return offset;
}

/**
 * Gets element's y position relative to the visible viewport.
 */
function getAbsoluteOffsetTop(el) {
  let offset = 0;
  let currentElement = el;

  while (currentElement !== null) {
    offset += currentElement.offsetTop;
    offset -= currentElement.scrollTop;
    currentElement = currentElement.offsetParent;
  }

  return offset;
}

Upvotes: 1

karlsebal
karlsebal

Reputation: 1731

function inViewport(element) {
    let bounds = element.getBoundingClientRect();
    let viewWidth = document.documentElement.clientWidth;
    let viewHeight = document.documentElement.clientHeight;

    if (bounds['left'] < 0) return false;
    if (bounds['top'] < 0) return false;
    if (bounds['right'] > viewWidth) return false;
    if (bounds['bottom'] > viewHeight) return false;

    return true;
}

source

Upvotes: 9

jordancooperman
jordancooperman

Reputation: 2011

jQuery implements this quite elegantly. If you look at the source for jQuery's offset, you'll find this is basically how it's implemented:

var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;

return {
    top: rect.top + win.pageYOffset,
    left: rect.left + win.pageXOffset
};

Upvotes: 14

GURU PRASAD
GURU PRASAD

Reputation: 483

var element =  document.querySelector('selector');
var bodyRect = document.body.getBoundingClientRect(),
    elemRect = element.getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top;

Upvotes: 26

Arif
Arif

Reputation: 6478

Sometimes getBoundingClientRect() object's property value shows 0 for IE. In that case you have to set display = 'block' for the element. You can use below code for all browser to get offset.

Extend jQuery functionality :

(function($) {
    jQuery.fn.weOffset = function () {
        var de = document.documentElement;
        $(this).css("display", "block");
        var box = $(this).get(0).getBoundingClientRect();
        var top = box.top + window.pageYOffset - de.clientTop;
        var left = box.left + window.pageXOffset - de.clientLeft;
        return { top: top, left: left };
    };
}(jQuery));

Use :

var elementOffset = $("#" + elementId).weOffset();

Upvotes: 2

Sunil
Sunil

Reputation: 21406

I am assuming an element having an id of btn1 exists in the web page, and also that jQuery is included. This has worked across all modern browsers of Chrome, FireFox, IE >=9 and Edge. jQuery is only being used to determine the position relative to document.

var screenRelativeTop =  $("#btn1").offset().top - (window.scrollY || 
                                            window.pageYOffset || document.body.scrollTop);

var screenRelativeLeft =  $("#btn1").offset().left - (window.scrollX ||
                                           window.pageXOffset || document.body.scrollLeft);

Upvotes: 3

Fabio Nolasco
Fabio Nolasco

Reputation: 7492

On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:

var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;

That allows me to get the real relative position of element on document, even if it has been scrolled.

Upvotes: 117

Himanshu P
Himanshu P

Reputation: 9925

The existing answers are now outdated. The native getBoundingClientRect() method has been around for quite a while now, and does exactly what the question asks for. Plus it is supported across all browsers (including IE 5, it seems!)

From MDN page:

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

You use it like so:

var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top = viewportOffset.top;
var left = viewportOffset.left;

Upvotes: 422

Waleed Eissa
Waleed Eissa

Reputation: 10513

Thanks for all the answers. It seems Prototype already has a function that does this (the page() function). By viewing the source code of the function, I found that it first calculates the element offset position relative to the page (i.e. the document top), then subtracts the scrollTop from that. See the source code of prototype for more details.

Upvotes: 2

Derek Swingley
Derek Swingley

Reputation: 8752

Edit: Add some code to account for the page scrolling.

function findPos(id) {
    var node = document.getElementById(id);     
    var curtop = 0;
    var curtopscroll = 0;
    if (node.offsetParent) {
        do {
            curtop += node.offsetTop;
            curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
        } while (node = node.offsetParent);

        alert(curtop - curtopscroll);
    }
}

The id argument is the id of the element whose offset you want. Adapted from a quirksmode post.

Upvotes: 20

Szere Dyeri
Szere Dyeri

Reputation: 15236

You can try:

node.offsetTop - window.scrollY

It works on Opera with viewport meta tag defined.

Upvotes: 6

rism
rism

Reputation: 12142

The function on this page will return a rectangle with the top, left, height and width co ordinates of a passed element relative to the browser view port.

    localToGlobal: function( _el ) {
       var target = _el,
       target_width = target.offsetWidth,
       target_height = target.offsetHeight,
       target_left = target.offsetLeft,
       target_top = target.offsetTop,
       gleft = 0,
       gtop = 0,
       rect = {};

       var moonwalk = function( _parent ) {
        if (!!_parent) {
            gleft += _parent.offsetLeft;
            gtop += _parent.offsetTop;
            moonwalk( _parent.offsetParent );
        } else {
            return rect = {
            top: target.offsetTop + gtop,
            left: target.offsetLeft + gleft,
            bottom: (target.offsetTop + gtop) + target_height,
            right: (target.offsetLeft + gleft) + target_width
            };
        }
    };
        moonwalk( target.offsetParent );
        return rect;
}

Upvotes: 5

Related Questions