Yahoo! Developer Network Home - Help

Site Search (YDN & YUIBlog):

# YUI Library Examples: Dom Collection: Using getXY

# Dom Collection: Using getXY

Clicking the button will use Dom's `getXY` method to get the position of the red element and pass it to the `setXY` method, which will move the blue element to that position.

View example in new window.

## Using getXY

`getXY`, part of the YUI Dom Collection, makes it easy to get an element's position relative to the document.

To illustrate the use of `getXY`, we'll create a `<div>` called `foo` and a `<div>` called `bar`. When the document is clicked, `foo` will move to the top left corner of `bar`.

Start with some simple CSS rules, markup for the demo elements, and a button to trigger the demo:

<style type="text/css"> #foo { background-color:#00f; height:10px; width:10px; } #bar { background-color:#f00; height:100px; width:100px; margin:0 100px 1em; } </style> <div id="foo"></div> <div id="bar"></div> <button id="demo-run">run</button>

Now we will define the function that moves `foo` to the `xy` position of `bar`. The only argument of the `getXY` method is either the ID of an HTMLElement, or an actual HTMLElement object. The `getXY` method returns an array containing two values: `[x, y]` where `x` is the distance from the left edge of the document, and `y` is the distance from the top edge of the document. The YUI Dom Collection provides a `setXY` that accepts an array in the same format.

<script type="text/javascript"> var move = function() { var xy = YAHOO.util.Dom.getXY('bar'); YAHOO.util.Dom.setXY('foo', xy); }; </script>

Next we will use the YUI Event Utility's `on` method to listen for clicks on the button.

YAHOO.util.Event.on('demo-run', 'click', move);

This is a simple example of how to use the `YAHOO.util.Dom.getXY` method. One of the powerful things about this is that regardless of what is influencing the element's position, be it positioning (absolute, relative, etc.), margins, an `offsetParent` (any positioned ancestor), or any other factors that may affect it, `getXY` will return a position in document coordinates (e.g. `[0, 0]` will be the upper left corner of the document).

### YUI Logger Output:

Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

### Dom Collection Examples:

### More Dom Collection Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings