Sign in

.getPosition()

Fetches and returns the dimensions and position of an element as coordinates.

Syntax

neon.getPosition([relativeto])

relativeto

This optional parameter specifies which other element the coordinates should be calculated as relative to. If not specified, the coordinates returned will be relative to the current viewport (visible portion of the page).  To get the position relative to the document, you can specify document here.

This function takes the same type of arguments as .select(). Please see that method for a description of its arguments.

Requirements

This method should be executed on a selection of elements. Please see the .select() method. Note that only the first element is used if there are multiple selected elements.

This method also allows the first selected object to be the global (Window) object, rather than an element. When this is the case, the position of the current viewport (visible area of the page) is returned. This can be used to get the dimensions of the viewport, or its position relative to another element.

Return value

This method returns an object describing the requested element's position and dimensions, with the following properties:

  • left, top

    The coordinates of the top left corner of the element's position, in pixels, as integers.

  • right, bottom
    The coordinates of the bottom right corner of the element's position, in pixels, as integers. The right bottom coordinates are inclusive, which allows right - left to equal the width of the item in pixels. Because of this, the pixel they point to is the first pixel outside of the element's bounding rectangle.

This method is not chainable.

Description

This method returns the position and dimensions of an element in a page or window.

Technically, the position it returns is that of the smallest rectangle that surrounds all parts of the element, including its padding and border but not its margins. Inline elements may not always be rectangular - for example, when they span multiple lines. Here, the bounding rectangle will be just big enough to contain all lines of the element.

By default, the position of the first selected element is calculated relative to the current viewport (visible portion of the window). This behaviour can be changed by use of the optional relativeto parameter.

Examples

// Get position of element relative to viewport
position = neon.select("div.myelement").getPosition();
// Get position of element relative to entire document
position = neon.select("div.myelement").getPosition(document);
// Get position of viewport relative to document
position = neon.select(window).getPosition(document);