[javascript] jQuery get the location of an element relative to window

Given an HTML DOM ID, how to get an element's position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent since the element may be inside an iframe or some other elements. I need to get the screen location of the element's rectangle (as in position and dimension) as it is currently being displayed. Negative values are acceptable if the element is currently off-screen (have been scrolled off).

This is for an iPad (WebKit / WebView) application. Whenever the user taps on a special link in an UIWebView, I am supposed to open a popover view that displays further information about the link. The popover view needs to display an arrow that points back to the part of the screen that invokes it.

This question is related to javascript jquery ipad webkit webview

The answer is


This sounds more like you want a tooltip for the link selected. There are many jQuery tooltips, try out jQuery qTip. It has a lot of options and is easy to change the styles.

Otherwise if you want to do this yourself you can use the jQuery .position(). More info about .position() is on http://api.jquery.com/position/

$("#element").position(); will return the current position of an element relative to the offset parent.

There is also the jQuery .offset(); which will return the position relative to the document.


    function trbl(e, relative) {
            var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);

            return {
                    t : r.top    + relative['scrollTop'] (),
                    r : r.right  + relative['scrollLeft'](),
                    b : r.bottom + relative['scrollTop'] (),
                    l : r.left   + relative['scrollLeft']() 

            }
    }

    // Example
    trbl(e, window);

Try this to get the location of an element relative to window.

_x000D_
_x000D_
        $("button").click(function(){_x000D_
            var offset = $("#simplebox").offset();_x000D_
            alert("Current position of the box is: (left: " + offset.left + ", top: " + offset.top + ")");_x000D_
        });
_x000D_
    #simplebox{_x000D_
        width:150px;_x000D_
        height:100px;_x000D_
        background: #FBBC09;_x000D_
        margin: 150px 100px;_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button type="button">Get Box Position</button>_x000D_
    <p><strong>Note:</strong> Play with the value of margin property to see how the jQuery offest() method works.</p>_x000D_
    <div id="simplebox"></div>
_x000D_
_x000D_
_x000D_

See more @ Get the position of an element relative to the document with jQuery


function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers


TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.


Try the bounding box. It's simple:

var leftPos  = $("#element")[0].getBoundingClientRect().left   + $(window)['scrollLeft']();
var rightPos = $("#element")[0].getBoundingClientRect().right  + $(window)['scrollLeft']();
var topPos   = $("#element")[0].getBoundingClientRect().top    + $(window)['scrollTop']();
var bottomPos= $("#element")[0].getBoundingClientRect().bottom + $(window)['scrollTop']();

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ipad

What is correct media query for IPad Pro? iPad Multitasking support requires these orientations How to restrict UITextField to take only numbers in Swift? How to present a modal atop the current view in Swift Presenting a UIAlertController properly on an iPad using iOS 8 Detect current device with UI_USER_INTERFACE_IDIOM() in Swift HTML5 Video tag not working in Safari , iPhone and iPad Install .ipa to iPad with or without iTunes How to hide UINavigationBar 1px bottom line How to fix UITableView separator on iOS 7?

Examples related to webkit

com.apple.WebKit.WebContent drops 113 error: Could not find specified service HTML5 Video autoplay on iPhone What does the shrink-to-fit viewport meta attribute do? Chrome / Safari not filling 100% height of flex parent How to style HTML5 range input to have different color before and after slider? What are -moz- and -webkit-? Video auto play is not working in Safari and Chrome desktop browser Rotate and translate Background color not showing in print preview Blurry text after using CSS transform: scale(); in Chrome

Examples related to webview

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead? Android Webview gives net::ERR_CACHE_MISS message Swift Open Link in Safari How to load html string in a webview? how to display progress while loading a url to webview in android? Download file inside WebView How to pass html string to webview on android how to get html content from a webview? Android webview slow Android WebView not loading an HTTPS URL