Link to home
Get AccessLog in
Avatar of elepil
elepil

asked on

JavaScript/jQuery: How to get the x-y coordinates of an element

I need to be able to center a dynamically-generated HTML element within a container that has both vertical and horizontal scrollbars. In this pursuit, I need to be able to get the container and target element's width and height (which I know how to do), and the target element's x-y coordinates. But when I try to access the target element's 'left' and 'top' properties, I get 'auto':

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(function() {
        var cell = $("#cell");
        console.log(cell.css("left")); // returns 'auto'
        console.log(cell.css("top")); // returns 'auto'
    });

</script>
<style>
</style>
</head>
<body>    
    <table>
        <tr><td><div id="cell">A Cell</div></td></tr>
    </table>
</body>
</html>

Open in new window


Can anyone please show me how to get the 'left/top' or x/y coordinates of an HTML element? Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Tom Beck
Tom Beck
Flag of United States of America image

Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Avatar of elepil
elepil

ASKER

Thank you, Tom!
You're welcome. Thanks for the points.