Showing posts with label position. Show all posts
Showing posts with label position. Show all posts

Sunday, September 3, 2017

jQuery get exact position of element | get exact left top position of jQuery element

Below is code snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Position of Element</title>
    <script src="jquery-2.1.4.js"></script>
    <script type="text/javascript">
        $(document.body).ready(function() {
            var body = $(document.body), element = body.find(".element"),
                    log = body.find(".log");
            var rect = element[0].getBoundingClientRect();
            log.append("<p>LEFT==" + rect.left + "</p>");
            log.append("<p>TOP==" + rect.top + "</p>");
            log.append("<p>RIGHT==" + rect.right + "</p>");
            log.append("<p>BOTTOM==" + rect.bottom + "</p>");
            log.append("<p>WIDTH==" + rect.width + "</p>");
            log.append("<p>HEIGHT==" + rect.height + "</p>");
        });
    </script>
</head>
<body style="margin:0">
<div style="position:relative;width:100%;height:100%;margin:0">
    <div class="element" style="position:absolute;margin:0;left:170px;top:200px;border:1px solid red;width:100px;height:30px;"></div>
</div>
<div class="log" style="font-weight:bold;"></div>
</body>
</html>

And output is below:


Saturday, May 9, 2015

jQuery get an elements position or offset according to some parent element


$.fn.offsetRelative = function(top){
    var $this = $(this);
    var $parent = $this.offsetParent();
    var offset = $this.position();
    
    // add scroll
    offset.top += $this.scrollTop()+$parent.scrollTop();
    offset.left += $this.scrollLeft()+$parent.scrollLeft();
    if(!top) {
        // Didn't pass a 'top' element
        return offset;
    } else if($parent.get(0).tagName == "BODY") {
        // Reached top of document
        return offset;
    } else if($($(top), $parent).length) {
        // Parent element contains the 'top' element we want the offset to be relative to
        return offset;
    } else if($parent[0] == $(this).closest(top)[0]) {
        // Reached the 'top' element we want the offset to be relative to
        return offset;
    } else {
        // Get parent's relative offset
        var parent_offset = $parent.offsetRelative(top);
        offset.top += parent_offset.top;
        offset.left += parent_offset.left;
        return offset;
    }
};

JSFiddle link