Clicking the document will use Dom's
setXY method to position the element to the click point.
To illustrate the use of
setXY, we'll create a single
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
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).
Note: Logging and debugging is currently turned off for this example.