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.
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:
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.
Next we will use the YUI Event Utility's on
method to listen for clicks on the button.
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).
You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.
Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.
Copyright © 2011 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings