YUI Library Examples: Dom Collection: Using setXY

Dom Collection: Using setXY

Clicking the document will use Dom's setXY method to position the element to the click point.

Using setXY

setXY, part of the YUI Dom Collection, makes it easy to position an element relative to the document.

To illustrate the use of setXY, we'll create a single <div> called foo that positions itself to the cursor when the document is clicked.

The first thing we need to do is load the Dom source file and dependencies:

Add some simple CSS rules and markup for the demo element and a button to activate the demo:

Now we will define the function that moves the element based on the position of the click. The first argument of the setXY method is either the ID of an HTMLElement, or an actual HTMLElement object. The second argument is 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 Event Utility provides a getXY method that accepts an event object as an argument, and returns the position of the cursor at the time of the click. The returned position is an array in the same format as the setXY array, so it can be fed directly to the setXY method.

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

This is a simple example of how to use the YAHOO.util.Dom.setXY 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, and offsetParent (any positioned ancestor), or other factors that may affect it, setXY will ensure the final position is accurate 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.

More Dom Collection Resources:

Copyright © 2007 Yahoo! Inc. All rights reserved.

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