Module: UWA/Element

UWA/Element

Cross-Platform API for DOM Elements manupilation.

Features
  • Element's className manipulation.
    • addClassName
    • hasClassName
    • toggleClassName
  • Element's events manipulation, including many polyfills and custom events
    • addEvent
    • triggerEvent
    • removeEvent
  • Element's selector polyfills and enhancements
    • getElements
    • getElement
    • match
  • Element's styles manipulation including CSS3 polyfills (e.g no need preffix)
    • setStyles
    • setStyle
    • getStyle
  • Element's dimensions and position caculations
    • getOffsets
    • getSize
    • getPosition
    • getScrolls
    • isInViewport
  • Easy HTML content injection using JSON object instead of string
    • addContent
    • setContent
    • inject
    • grab

Example

var myElement = UWA.createElement('ul', {
    'class': 'myElement items',
    html: [
        {
            tag: 'li',
            'class': 'item',
            text: 'My first item'
        },
        {
            tag: 'li',
            'class': 'item',
            text: 'My second item'
        }
    ],
    styles: {
        borderRadius: '5px',
        background: 'red'
    },
    events: {
        click: function (event) {

            // Handle click on li here
            var eventElement = UWA.Event.getElement(event);
        }
    }
}).inject(widget.body);

Namespaces

Element.Events

Index

Methods

<static> Element.create(tagName, options) → {Element}

Create a DOM Element with UWA.Element methods.

Example
var myElement = Element.create('a', {
   'class': 'myClass1 myClass2',
   html: 'Hello World',
   styles: {
     ...
   },
   events: {
       click: function(event) {
           UWA.Event.stop(event);
           ...
       }
   }
});
Parameters
Name Type Description
tagName String

The element tag name (eg: 'div')

options Object

Element attributes and options

Returns

The new Element.

Type
Element

<static> Element.extend(element) → {Element}

Extent a DOM Element with UWA.Element methods.

Example
var el = Element.extend(document.getElementById('myElementId'));
Parameters
Name Type Description
element Element

The Element to extend

Returns

the extended Element.

Type
Element

set(name, value) → {Element}

Shortcut to manipulates the element using setter methods.

Example of name parameter
name Description
"html" set the html (See setHTML)
"events" set the events (See addEvents)
"class" set the full classname

Any name who match a method "UWA.Element.prototype.set[Name]" will call this method with the value, other names will call the setAttribute method.

Example
var myElement = UWA.createElement('a');

// Add some attributes, fill with text, add some events
myElement.set({
   href: "http://...",
   title: "MyLink",
   text: "pouete",
   events: {
       click: function () { }
   }
});

// Key / value signature
myElement.set('styles', {
   color: 'red'
});

// Key / value signature with more than one argument
myElement.set('style', 'background-color', 'blue');
Parameters
Name Type Description
name String | Object

if this is a String, it is the name of the shortcut to set. - if this is an Object, it should be a hash associating names to values to set.

value *

The value to set

Returns

The current Element instance.

Type
Element

setAttributes(attributes) → {Element}

Sets the attributes values of the element. Attributes are passed as either a hash or a name/value pair.

Example
var myElement = UWA.createElement('a');

// Add "href" and "title" attributes
myElement.setAttributes({
   href: "http://...",
   title: "MyLink"
});
// Will render "<a href="http://..." title="MyLink"></a>"
Parameters
Name Type Description
attributes Object

Attributes hash or a name/value pair

Returns

The current Element instance.

Type
Element

getTagName() → {String}

Get the element tagName in lowercase.

Example
var myElement = UWA.createElement('div');
myElement.getTagName();
// Will return "div"
Returns

The current element tagName.

Type
String

setText(text) → {Element}

Replace element's existing content by a new text node.

Example
var myText = UWA.createElement('p', {
   text: "Hello!"
});

// Replace element text by "Loading...".
myText.setText("Loading...");
// Will render "<p>Loading...</p>"
Parameters
Name Type Description
text String

The text value

Returns

The current Element instance.

Type
Element

appendText(text) → {Element}

Adds a new text node at the end of the element's existing content.

Example
var myText = UWA.createElement('p', {
   text: "Hello"
});

// Append " World!" text into the element.
myText.appendText(" World!");
// Will render "<p>Hello World!</p>"
Parameters
Name Type Description
text String

The text value

Returns

The current Element instance.

Type
Element

getText() → {String}

Get the inner text of the element.

Example
var myContent = UWA.createElement('p', {
   html: 'Hello World!'
});

myContent.getText();
// Will return "Hello World!"
Returns

text contained by the element.

Type
String
See:

setContent() → {Element}

Replace the content of the element by another.

Content parameter could be:

  • a String, considered as XHTML
  • a DOM Element
  • an Object used to create an DOM element by using the 'tag' field as tag and other fields as properties
  • an Array of Objects used to create multiple DOM elements
  • each argument can be: String/Object/Array content: the content to set to the element.
Examples
Setup code (required for all examples)
var myContent = UWA.createElement('div');
Insert an element using Object syntax
myContent.setContent({
   tag: 'a',
   href: 'http://www.example.com',
   text: 'My Link',
   styles: {
       color: 'red'
   },
   events: {
      click: function (event) {
           // My Click Handler
           UWA.Event.stop(event);
      }
   }
});

Will render:

<div>
   <a style="color: red;" href="http://www.example.com">My Link</a>
</div>
Insert elements using Array syntax
myContent.setContent([
   {
       tag: 'div',
       'class': 'myHeader'
   },
   {
       tag: 'div',
       'class': 'myContent',
       html: [
           {
               tag: 'a',
               text: 'My Link',
               styles: {
                   color: 'red'
               },
               events: {
                   click: function (event) {
                       // My Click Handler
                       UWA.Event.stop(event);
                  }
               }

           }
       ]
   },
   {
       tag: 'div',
       'class': 'myFooter'
   },
]);

Will render:

<div>
   <div class="myHeader"></div>
   <div class="myContent">
       <a>My Link</a>
   </div>
   <div class="myFooter"></div>
</div>
Using String considered as XHTML (bad pratice)
myContent.setContent('<a href="http://www.example.com">My Link</a>');
Returns

The current Element instance.

Type
Element

addContent() → {Element}

Add content to current Element.

Content parameter could be:

  • a String, considered as XHTML
  • a DOM Element
  • an Object used to create an DOM element by using the 'tag' field as tag and other fields as properties
  • an Array of Objects used to create multiple DOM elements
  • each argument can be: String/Object/Array content: the content to add to the element.
Example
See UWA.Element.setContent method.
Returns

the current Element instance.

Type
Element

setHTML(html) → {Element}

Sets the content of the element from a valid XHTML String.

Notes about HTML vs XHTML

In most of the UWA environments HTML have to be valid XHTML.

  • XHTML is fundamentally different from HTML, despite looking very similar.
  • XHTML is XML, which means that the syntax rules are slightly different.
  • There are things you can do in XHTML which you cannot do in HTML.
  • There are things you can do in HTML which you cannot do in XHTML.
  • There are differences concerning CSS.
  • There are differences concerning client-side scripting (e.g., JavaScript).
Invalid XHTML
<img src="...">
<input name="" value="" >
<br>
Valid XHTML
<img src="..." />
<input name="" value="" />
<br />
Example
// Your existing element
var myContent = UWA.createElement('div', {
   html: '<p>Loading...<p/>'
});

myContent.setHTML('<p>Ready!<p/>');
Parameters
Name Type Description
html String

A valid XHTML String

Returns

The current Element instance.

Type
Element
See:

getHTML() → {String}

Gets the content of the element.

Example
// Your existing elements tree
var myContent = UWA.createElement('div', {
   html: {
       tag: 'p',
       text: 'Loading...'
   }
});

myContent.getHTML();
// Will return "<p>Loading...<p/>"
Returns

The current Element innerHTML value.

Type
String

inject(injected, where) → {Element}

Inject, or insert, the element at a particular place relative to the Element's children (specified by the second the argument, default is "bottom").

Example
// Your existing elements tree
var myFriendList = UWA.createElement('ul', {
   html: {
       tag: 'li',
       text: 'John Doe'
   }
});

// Inject to the bottom (default)
UWA.createElement('li', {
   text: 'Marla Singer'
}).inject(myFriendList, 'bottom');

// Inject to the top
UWA.createElement('li', {
   text: 'Brendan Eich'
}).inject(myFriendList, 'top');

// Inject before
UWA.createElement('h1', {
   text: 'My Friends'
}).inject(myFriendList, 'before');

Will render:

<h1>My Friends</h1>
<ul>
   <li>Brendan Eich</li>
   <li>John Doe</li>
   <li>Marla Singer</li>
</ul>
Parameters
Name Type Description
injected Element

The element to inject

where String

The place to inject this Element Can be 'top', 'bottom', 'after', or 'before'.

Returns

The current Element instance.

Type
Element

grab(element, where) → {Element}

Works as inject, but in reverse.

Append the element at a particular place relative to the element's children (specified by the where parameter).

Example
// Your existing elements tree
var myFriendList = UWA.createElement('ul', {
   html: {
       tag: 'li',
       text: 'John Doe'
   }
});

// Insert element into myFriendList
myFriendList.grab(UWA.createElement('li', {
   text: 'Marla Singer'
}));

Will render:

<ul>
   <li>John Doe</li>
   <li>Marla Singer</li>
</ul>
Parameters
Name Type Description
element Element

The element to inject

where String

The place to inject this Element Can be 'top', 'bottom', 'after', or 'before'.

Returns

The current Element instance.

Type
Element

isInjected(parent) → {Boolean}

Check if element is injected into another element, by default the documentElement.

Example
// Your existing element
var myContent = UWA.createElement('div', {
   html: {
       tag: 'p',
       text: 'Loading...'
   }
});

myContent.isInjected();
// Will return `false`

myContent.inject(widget.body);
myContent.isInjected();
// Will return `true` because it's inside the DOM tree
Parameters
Name Type Description
parent Element

The parent element that sould containt the element, by default it's ownerDocument.documentElement.

Returns

true if has document.body into the parents tree else false.

Type
Boolean
See:

empty(destroyChildren) → {Element}

Empty an element of all his children. Children should/could may not be used after this.

Example
// Your existing element
var myContent = UWA.createElement('div', {
   html: {
       tag: 'p',
       text: 'Loading...'
   }
});

// Remove the element children
myContent.empty();
Parameters
Name Type Argument Default Description
destroyChildren Boolean <optional>
false

true to remove all events from children (see UWA.Element.destroy).

Returns

The current Element instance.

Type
Element

remove() → {Element}

Detach the element from the parent and returns it.

Returns

The current Element instance.

Type
Element

destroy()

Destroy the element and its children. Remove all events from elements and children and remove them from the document. Element and it's children should/could may not be used after this.

getParent(selector) → {Element}

Return the parent node of the element.

Parameters
Name Type Argument Description
selector String <optional>

Get the first parent who matches the selector.

Returns

The parent node, null if the parent was not found.

Type
Element

getParents(selector) → {Array}

Get the parent nodes of the element

Parameters
Name Type Argument Description
selector String <optional>

Filter parents matching this selector

Returns

the parent nodes

Type
Array

getClosest(String) → {Element}

Get the closest element matching a selector. If the element does not match the selector, get the first matching parent.

Parameters
Name Type Description
String selector

The selector to use

Returns

The closest element, or null if it was not found.

Type
Element

getChildren() → {Array}

Get collection of the element's child nodes.

Returns

Collection of the element's child nodes.

Type
Array

getDocument() → {Document}

Get the document of the current element.

Returns

Document element of the current element.

Type
Document

getWindow() → {Window}

Get the window of the current element.

Returns

window element of the current element.

Type
Window

getOffsetParent() → {Element}

Returns the parent of the element that is positioned, if there is one.

Notes:

This method fix broken offsetParent on IE < 8 using featured detection.

Returns

The first positioned element's parent node.

Type
Element

getElements(selector)

Gets all descendants elements whose match a CSS selector. Behaves like the Element.querySelectorAll except for queries starting with ">", "~" and "+".

Example
  • Setup code (required for all examples)
// Create your elements tree
var element = UWA.createElement('div', {
   html: [
       {
           tag: 'h1',
           html: {
               tag: 'a',
               text: 'My App Title...'
           }
       },
       {
           tag: 'div',
           'class': 'highlighted',
           html: {
               tag: 'ul',
               html: [
                   {
                       tag: 'li',
                       html: {
                           tag: 'a',
                           text: 'My first Nav'
                       }
                   },
                   {
                       tag: 'li',
                       html: {
                           tag: 'a',
                           text: 'My second Nav'
                       }
                   }
               ]
           }
       }
   ]
});

Will render:

<div>
   <h1>
       <a>My App Title...</a>
   </h1>
   <div class="highlighted">
       <ul>
           <li><a>My first Nav</a></li>
           <li><a>My second Nav</a></li>
       </ul>
   </div>
</div>
  • Gets descendants elements whose match CSS selector
// Get all anchors in the element
element.getElements('a');

// Get all elements with "myClass" class
element.getElements('.myClass');

// Get all anchors with "myClass" class
element.getElements('a.myClass');

// Get all anchors with a title attribute in the element
element.getElements('a[title]');

// Get all "p" children elements under a container,
// whose parent is a div that contains the class 'highlighted'
element.getElements('div.highlighted > p');
Parameters
Name Type Description
selector String

The CSS selector to use (could be more than one rule)

Returns

Array of <UWA.Element> that matched.

getElement(selector) → {Element}

Gets the first descendant element who matches a CSS selector. Behaves like the Element.querySelectorAll except for queries starting with ">", "~" and "+".

Example
  • Setup code (required for all examples)
var element = UWA.createElement('div', {
    html: [
        {
            tag: 'h1',
            html: {
                tag: 'a',
                text: 'My App Title...'
            }
        },
        {
            tag: 'div',
            'class': 'highlighted',
            html: {
                tag: 'ul',
                html: [
                    {
                        tag: 'li',
                        html: {
                            tag: 'a',
                            text: 'My first Nav'
                        }
                    },
                    {
                        tag: 'li',
                        html: {
                            tag: 'a',
                            text: 'My second Nav'
                        }
                    }
                ]
            }
        }
    ]
});

Will render:

<div>
   <h1>
       <a>My App Title...</a>
   </h1>
   <div class="highlighted">
       <ul>
           <li><a>My first Nav</a></li>
           <li><a>My second Nav</a></li>
       </ul>
   </div>
</div>
  • Gets first descendant element whose match CSS selector
// Get the first anchor in the element
element.getElement('a');

// Get the first element with "myClass" class
element.getElement('.myClass');

// Get the first anchor with "myClass" class
element.getElement('a.myClass');

// Get the first anchor with a title attribute in the element
element.getElement('a[title]');

// Get the first "p" children element under a container,
// whose parent is a div that contains the class 'highlighted'
element.getElement('div.highlighted > p');
Parameters
Name Type Description
selector String

The CSS selector to use (could be more than one rule)

Returns
  • <UWA.Element> that matched.
Type
Element

match(selector, root) → {Boolean}

Check if the element matches a CSS selector.

Behaves like the Element.matchesSelector but also accepts queries starting with ">", "~" and "+".

Example
// Without a root, this is not very usefull
element.match('> *'); // the element have a parent
element.match('+ ul'); // the element is an UL with a previous sibling

// With a root, everything makes sense
element.match('> *', root); // the element is a direct child of the root

// .header in the container element
element.match('> .header', container);
// the element is the header of the container, and not a random element
Parameters
Name Type Description
selector String

The CSS selector to use (could be more than one rule)

root Element

optional - Limit the selection to children of this element

Returns
  • wether or not the element matches the selector
Type
Boolean

hasClassName(className) → {Bool}

Checks whether element has the given CSS className.

Example
// Your existing element
var element = UWA.createElement('div', {
    'class': 'myCSSClassName'
});

element.hasClassName('myCSSClassName');
// Will return true

element.hasClassName('myMissingClassName');
// Will return false
Parameters
Name Type Description
className String

the className to check.

Returns
  • true if element has className else false.
Type
Bool

addClassName(className) → {Element}

Adds a CSS class to element.

Example
// Your existing element
var myElement = UWA.createElement('div', {
    'class': 'myCSSClassName'
});

// Add new "myCSSClassName" className
myElement.addClassName('myCSSClassName');
Parameters
Name Type Description
className String

the className to add.

Returns
  • the current Element instance.
Type
Element

removeClassName(className) → {Element}

Removes element's CSS className.

Example
// Your existing element
var myElement = UWA.createElement('div', {
    'class': 'myCSSClassName'
});

// Remove existing "myCSSClassName" className
myElement.removeClassName('myCSSClassName');
Parameters
Name Type Description
className String

the className to remove.

Returns
  • the current Element instance.
Type
Element

toggleClassName(className, force) → {Element}

Add or remove the passed in class name to the element, depending on whether or not it's already present.

Example
// Your existing element
var myElement = UWA.createElement('div', {
    'class': 'myCSSClassName'
});

// Remove exiting "myCSSClassName" className
myElement.toggleClassName('myCSSClassName');

// Add missing "myCSSClassName" className
myElement.toggleClassName('myCSSClassName');
Parameters
Name Type Description
className String

The class to add or remove.

force Boolean

force add (if true) or remove the class name.

Returns
  • the current Element instance.
Type
Element

setStyle(property, value) → {Element}

Modify element's CSS style property.

Example
// Your existing element
var myElement = UWA.createElement('div', {
    styles: {
        color: 'red'
    }
});

// Update "color" style
myElement.setStyle('color', 'blue');
Parameters
Name Type Description
property String

style property name.

value String

style property value.

Returns
  • the current Element instance.
Type
Element

setStyles(attributes) → {Element}

Modifies element's CSS style properties. Styles are passed as either a hash or a name/value pair.

Example
// Your existing element
var myElement = UWA.createElement('div', {
    styles: {
        color: 'red',
        padding: '5px'
    }
});

// Update "padding" and "color" styles
myElement.setStyle({
    color, 'blue',
    padding: '10px'
);
Parameters
Name Type Description
attributes Object

styles hash or a name/value pair.

Returns
  • the current Element instance.
Type
Element

getStyle(property, computed) → {String}

Get element's CSS style property value. By default it will return the CSS style property value computed by the browser.

Example
Setup code
<!-- Your CSS rule -->
<style type="text/css">
    div.myClass {
        padding: 10px;
    }
</style>
Get elements style value
// Your existing element
var myElement = UWA.createElement('div', {
    'class': 'myClass',
    styles: {
        color: 'red'
    }
});

myElement.getStyle('color');
// Will return "red"

// Using computed style
myElement.getStyle('padding');
// Will return "10px"

// Disable computed style
myElement.getStyle('padding', true);
// Will return ""
Parameters
Name Type Description
property String

style property name (e.g "color", "display", "top", ...).

computed Boolean

retrieve CSS style property value computed by the browser (e.g default is true).

Returns

the style property value (e.g "none", "red", "10px", ...).

Type
String
See:

getStyles(property, computed) → {Object}

Get element's CSS styles value. By default it will return the CSS style value computed by the browser.

Parameters
Name Type Description
property Array

style properties names.

computed Boolean

retrieve CSS style property value computed by the browser (e.g default is true).

Returns
  • styles properties value indexed by property name.
Type
Object

getStyleName(String, Boolean) → {String}

Get CSS style properties names for modern CSS3 property usage. Perform feature detection on properties names, to add vendor prefix (e.g Moz, Ms, Webkit).

Support vendor prefix for following CSS style property name: box-shadow, mask, box-shadow, mask, border-radius, user-select, box-sizing, transition, transition-timing-function, transition-duration, transition-delay, transition-property, transform, border-image, text-stroke, font-smoothing, text-fillcolor, appearance, text-shadow, transform-style, perspective, overflow-scrolling

Example
// Your existing element
var myElement = UWA.createElement('div');

myElement.getStyleName('border-radius');
// Will return "WebkitBorderRadius" on Webkit browsers
// Will return "OBorderRadius" on Opera browsers
// Will return "MozBorderRadius" on Firefox browsers
// Will return "MsBorderRadius"] on IE browsers

myElement.getStyleName('float');
// Will return "cssFloat" on main engines
// Will return "styleFloat" on IE browsers
Parameters
Name Type Description
String

property: style property name.

Boolean

noCamelCase: do not apply camelcase on results properties.

Returns
  • the style name.
Type
String

getOpacity(computed) → {Float}

Get element's CSS style opacity value.

Parameters
Name Type Description
computed Boolean

retrieve opacity value computed by the browser (e.g default is true).

Returns
  • the current element's CSS style opacity property value.
Type
Float

setOpacity(opacity) → {Element}

Set element's CSS style opacity value.

Note:

Opacity 0 and visibily hidden have not the same behavior.

Parameters
Name Type Description
opacity Float

the requested element's CSS style opacity property new value.

Returns
  • the current Element instance.
Type
Element

hide() → {Element}

Hides and returns element, by setting "display" style property to "none".

Returns
  • the current Element instance.
Type
Element

show() → {Element}

Reveal and return element, by setting "display" style property to right value.

Note:

The element will be revealed immediately, with no animation. This is roughly equivalent to calling element.setStyle('display', 'block'), except that the display property is restored to whatever it was initially.

Returns
  • the current Element instance.
Type
Element

toggle(force) → {Element}

Toggles the visibility of element.

Parameters
Name Type Description
force Boolean

force show (if true) or hide the element.

Returns
  • the current Element instance.
Type
Element

isHidden() → {Boolean}

Check wether this element is hidden by UWA.Element.hide.

Returns
Type
Boolean

setTranslate(y, x) → {Element}

Translate the position of element to X and Y parameters.

Note:

Translate element Using translate3d/translate or top/left depending the current DOM available feature.

Parameters
Name Type Description
y Number

new y/top coordonate.

x Number

new x/left coordonate.

Returns
  • the current Element instance.
Type
Element

getComputedSize(arguments)

Compute the size of a list of style properties

Example
// Your existing element
var myElement = UWA.createElement('div', {
    styles: {
        border: '1px solid red',
        padding: '2px'
    }
});

myElement.getComputedSize('borderLeftWidth', 'paddingLeft');
// Will return 3

myElement.getComputedSize('borderWidth');
// Will return 2
Parameters
Name Type Description
arguments String

some CSS properties.

getScrolls() → {Object}

Returns either the width and height in pixels of the content of an element or the width and height of the element itself, whichever is greater.

Example
// Your existing element
var myElement = UWA.createElement('div');

// Get Scrolls values
var myScrolls = myElement.getScrolls();

// myOffsets Object value (properties values depending the context)
{
    with: 417,
    height 53,
    top: 0,
    left 0
}
Returns
  • Object with "with, "height", "top, "left" properties.
Type
Object
See:

getOffsets() → {Object}

Gets the cumulative offsets of the x and y positions (or the cumulative top and left) of element, the position of the element will be relative to the document.

This function is helpful if you want to position things around a certain element.

Example
// Your existing element
var myElement = UWA.createElement('div');

// Get Offsets values
var myOffsets = myElement.getOffsets();

// myOffsets Object value (properties values depending the context)
{
    x: 417,
    y 53
}
Returns
  • Object with "y" and "x" properties.
Type
Object
See:

getPosition(relative, where) → {Object}

Gets the cumulative offsets of the x and y positions (or the cumulative top and left) of element, by default the position of the element will be relative to the offsetParent (see <getOffsetParent>).

This function is helpful if you want to position things around a certain element.

Example
// Your existing element
var myElement = UWA.createElement('div');

// Get Position values
var myPosition = myElement.getPosition();

// myPosition Object value (properties values depending the context)
{
    x: 7,
    y 170
}
Parameters
Name Type Description
relative Element

(optional) the position of the element will be relative. If Element, get the position relative to this esement. If false, get the position relative to the offsetParent (see <getOffsetParent>).

where String/Object

(optional) set the origin of the position. You can specify a corner (ex: { x: 'top', y: 'left' }), or the center of a side (ex: {x: 'center', y: 'top'} or simply 'center' for the center of the box.

Returns
  • Object with "y" and "x" properties (e.g {x: Number, y: Number}).
Type
Object

setPosition(position, options) → {Element}

Sets the position of an Element

Example
// Simple usage
myElement.setPosition({x: 10, y: 20}, {
    relative: document.body,
    boundary: 'auto',
    boundaryMargin: 4
});

// Advanced usage
myElement.setPosition({x: 10, y: 20}, {
    relative: document.body,
    boundary: 'auto',
    fit: function (boundary, position) {
        var elSize = Element.getSize.call(this).height,

            // Compute the free space on each direction
            hasSpaceAbove = position.y - boundary.y >= elSize,
            hasSpaceBelow = boundary.y + boundary.height - position.y >= elSize;

        if (!hasSpaceBelow && hasSpaceAbove) {
            // If there is no space below and some space above, go above
            position.y -= elSize;
        }
    }
});
Parameters
Name Type Description
position Object/Array

an object or a list of object with the properties 'x' and 'y' representing the coordinates of the element. If this is an array and there is a boundary specified (see options parameter), it will pick the best position to fit the element in the boundary.

options Object

a JavaScript object containing setting/value pairs.

Properties
Name Type Argument Description
relative Element <optional>

An Element to which position values will be relative to (default to first relative parent).

boundary Object | Element | String <optional>

Limit the position to a given zone. It can be: - an object {x, y, width, height} with coordinates relative to the relative option, - an Element - auto' will use the first parent with a overflow hidden or auto

boudaryMargin Element <optional>

An Element to which position values will be relative to (default to first relative parent).

fit String | Function <optional>

If a boundary is used, specify the strategy to use in order to fit the element into the boundary. - 'full' (default): adjust the final position to fit the whole element in the boundary - 'none': do not try to fit the element in the boundary (only the top left corner will have to be in the boundary). - 'resize-max': adjuste the max-width and max-height styles of the element in order to fit in the element. - a function: the function will be called with two parameters: one representing the boundary with its position (x/y) and its size (width/height), the second will be the position of the element (x/y). The context (this) is the current element. Coordinates are absolute in the page. You can change those objects in order to implement a custom behaviour to fit the element inside its boundary (for example, if the element does not fit below another element, you can change its position to display it above). See example below.

Returns
  • The current Element instance
Type
Element

getSize() → {Object}

Retrieve the height and width of an element.

Notes:

The width and height size is based on offset(Width|Height) that mean that it include border and padding edge (W3C Content edge).

To get the inner size (with no border and padding edge), use <getDimensions> innerWidth or innerHeight. To get the outer size (with margin edge), use <getDimensions> outerWidth or outerHeight.

Example
// Your existing element
var myElement = UWA.createElement('div', {
    styles: {
        height: '100px',
        width: '100px',
        padding: '10px',
        margin: '7px',
        border: '2px solid red'
    }
}).inject(widget.body);

// Get Size values
var mySize = myElement.getSize();

// mySize Object value
{
    height: 124, // innerHeight + paddingTop + paddingBottom + borderTopWidth + borderBottomWidth
    width: 124 // innerWidth + paddingLeft + paddingRight + borderLeftWidth + borderRightWidth
}
Returns
  • Object with "with and "height" properties.
Type
Object
See:

getDimensions() → {Object}

Compute various dimpensions of an element.

Notes:

If you consider only get the with and height properties use <UWA.Element.getSize> method it's faster.

Example
// Your existing element
var myElement = UWA.createElement('div', {
    styles: {
        padding: '10px',
        margin: '5px',
        height: '100px',
        width: '100px',
        border: '2px solid red'
    }
}).inject(widget.body);

// Get Dimensions values
var myDimensions = myElement.getDimensions();

// myDimensions Object value
{
    height: 124,        // based on offsetHeight
    width: 124          // based on offsetWidth
    innerHeight: 100,   // height - (paddingTop + paddingBottom + borderTopWidth + borderBottomWidth)
    innerWidth: 100     // width - (paddingLeft + paddingRight + borderLeftWidth + borderRightWidth)
    outerHeight: 134,   // height + marginTop + marginBottom
    outerWidth: 134     // width + marginLeft + marginRight
}
Returns
  • Object with "with and "height", "innerWidth" and "innerHeight", "outerWidth" and "outerHeight", "maxWidth" and "maxHeight" properties.
Type
Object

isInViewport(element, partially, checkForDisplay, axis) → {Boolean}

Check if an element is visible in the current element viewport and on the screen. By default it's check that the element is entirely visible.

Example
// Your existing elements
var myFirstElement = UWA.createElement('div', {
        styles: {
            position: 'absolute',
            top: '5px',
            left: '0px',
            width: '10px',
            height: '10px',
            background: 'red'
        }
    }),
    mySecondElement = UWA.createElement('div', {
        styles: {
            position: 'absolute',
            top: '5px',
            left: '0px',
            width: '10px',
            height: '10px',
            background: 'blue'
        }
    });

// Inject elements
myFirstElement.inject(widget.body);
mySecondElement.inject(widget.body);

// Check if myFirstElement is in the mySecondElement viewport
myFirstElement.isInViewport(mySecondElement);
// Will return true

// Move myFirstElement element
myFirstElement.setStyle('top', '10px');

// Check if myFirstElement is in the mySecondElement viewport
myFirstElement.isInViewport(mySecondElement);
// Will return false

// Check if myFirstElement is partially in the mySecondElement viewport
myFirstElement.isInViewport(mySecondElement, true);
// Will return true

// Check if myFirstElement is in the mySecondElement viewport, and is visible in the page
myFirstElement.isInViewport(mySecondElement, false, true);
Parameters
Name Type Description
element Element

the element to check visibility.

partially Boolean

if any part of the element is visible in the viewport or only entirely visible (default: false).

checkForDisplay Boolean

if the element is in the screen and visible (in a human way) (default: false).

axis String

optionnal specific axis to check ('x' or 'y') (default: both).

Returns
  • true if the element is in the current element viewport else false.
Type
Boolean

setData(key, data) → {Element}

Store arbitrary data associated with the current element. The data value will be serialized in JSON.

Example
// Your existing element
var myElement = UWA.createElement('div');

// Store data into element
myElement.setData('myStringKey', 'myString');
myElement.setData('myObjectKey', {
    name: 'Bob',
    age: '25'
});

Will rendering

<div data-my-string-key="&quot;myString&quot;"
     data-my-object-key="{&quot;name&quot;:&quot;Bob&quot;,&quot;age&quot;:&quot;25&quot;}">
</div>
Parameters
Name Type Description
key String

the data key name.

data String

the data key value.

Returns
  • the current Element instance.
Type
Element

getData(key) → {Element}

Retrieve arbitrary data associated with the current element.

Example
// Your existing element
var myElement = UWA.createElement('div');

// Store data into element
myElement.setData('myStringKey', 'myString');
myElement.setData('myObjectKey', {
    name: 'Bob',
    age: '25'
});

// Retrieve data
myElement.getData('myStringKey');
// Will return "myString"

myElement.getData('myObjectKey');
// Will return Object
Parameters
Name Type Description
key String

the data key name.

Returns

the data key value.

Type
Element

removeData(key) → {Element}

Remove arbitrary data associated with the current element.

Example
// Your existing element
var myElement = UWA.createElement('div');

// Store data into element
myElement.setData('myStringKey', 'myString');

// Remove data
myElement.removeData('myStringKey');

// Retrieve data
myElement.getData('myStringKey');
// Will return undefined
Parameters
Name Type Description
key String

the data key name.

Returns
  • the data key value.
Type
Element

Handle any children's external links element click events with a callback function.

Notes: For advanced and internal library usage only.

Parameters
Name Type Description
listener: Function

click callback function that will receive url for argument.

Returns
  • the current Element instance.
Type
Element

addEvent(event, listener, noCustomEvent, priority, useCapture) → {Element}

Register a single event listener on a single target.

Event delegation: Events can be delegated by specifying a CSS selector in the first element, next to the event name. For example, to call the function only if the user clicks on links contained in the element, you could use the event name "click a". Any string accepted by Element#match is valid (selectors starting by an operator > ~ +, separated by commas, ...). See example below.

Examples
Simple example:
// Your existing element
var myElement = UWA.createElement('a', {
    text: 'My Link'
}),

function myClickListener(event) {

     // Stop event propagation and prevent default.
     UWA.Event.stop(event);

     // The current scope of the listener function
     // is the element that we have added the event listener
     var myElement = this;

     // Store event position
     var position = UWA.Event.getPosition(event);
};

// Add a "click" event
myElement.addEvent('click', myClickListener);
Example using an EventListener:
// Your existing element
var myElement = UWA.createElement('a', {
        text: 'My Link'
   }),

   myEventListener = {
        myProperty : 'event listener',
        handleEvent : function (event) {
            UWA.log('"this" is scoped to this ' + this.myProperty);
        }
   };

// Add a "click" event
myElement.addEvent('click', myEventListener);

// When the event is triggered, the console display :
// "this" is the event listener object
Example using event delegation:
var myElement = UWA.createElement('div', {
    html: 'Event delegation is <strong>the best</strong>!'
});

// Bind the event on strong and span tags
myElement.addEvent('click strong,span', function () {
    UWA.log('You clicked on a strong or highlighted text!');
});

// You can change the element content at any time!
element.addContent(' and <span>this is highlighted</span>');

// Clicking on one of those tags will trigger the event
Events List:
Mouse
  • click - Mouse clicks an object.
  • mousedown - A mouse button is pressed.
  • mousemove - The mouse is moved.
  • mouseup - A mouse button is released.
Keyboard
  • keydown - A keyboard key is pressed.
  • keypress - A keyboard key is pressed or held down.
  • keyup - A keyboard key is released.
Frame / Window
  • abort - Fires when an object/image is stopped from loading before completely loaded.
  • error - An error occurs when loading a document or an image.
  • load - Fires when the target element and all of its content has finished loading.
  • resize - A window or frame is resized.
  • scroll - When something is scrolled.
  • unload - Fires when the target element or any of its content has been removed.
Forms
  • blur - An element loses focus.
  • change - The content of a field changes.
  • focus - An element gets focus.
  • select - When the user selects text in a text input field.
  • reset - When the user resets a form.
  • submit - When the user submits a form.
Touch
  • touchend - Happens every time a finger is removed from the screen.
  • touchmove - Happens as a finger already placed on the screen is moved across the screen.
  • touchstart - Happens every time a finger is placed on the screen.
  • touchcancel - Sent when the system cancels tracking for the touch.
Polyfill (See <UWA.Element.Event>)
  • mouseleave - Polyfill to support element mouseleave event.
  • mouseenter - Polyfill to support element mouseenter event.
  • mousewheel - Polyfill to support element mousewheel event.
  • transitionEnd - Polyfill to support element transitionEnd event.
Custom (See <UWA.Element.Event>)
  • resize - Custom event to support element resize detection.
  • update - Custom event to support element content update detection.
Others Event related methods:
  • <UWA.Event.stop> - Stop an Event from propagating and also executes preventDefault.
  • <UWA.Event.stopPropagation> - Stop the propagation of an event (this stops the event from bubbling up through the DOM).
  • <UWA.Event.preventDefault> - Prevent the default action of the event.
  • <UWA.Event.getElement> - Get element target to event parameter.
  • <UWA.Event.findElement> - Find an parent element of event target using tagName.
  • <UWA.Event.getPosition> - The "x" and "y" positions of the event, relative to the viewport.
Parameters
Name Type Argument Default Description
event String

the event name (e.g "click").

listener Function

the event listener function or an object implementing the EventListener interface.

noCustomEvent Boolean <optional>
false

Disable <UWA.Element.Event> custom and polyfill handler.

priority Number <optional>
0

The priority level of the callback listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added.

useCapture Boolean <optional>
false

use capture event instead of bubbling

Returns
  • the current Element instance.
Type
Element

addEvents(events, noCustomEvent, priority, useCapture) → {Element}

Register a multiple events listeners on a single target.

Example
// Your existing element
var myElement = UWA.createElement('a', {
        text: 'My Link'
   }),

   myEventListener = function (event) {

        // Stop event propagation and prevent default.
        UWA.Event.stop(event);

        // Get the Event type (click or touchstart into this example)
        var eventType = event.type;
   };

// Add "click" and "touchstart" events
myElement.addEvents({
    click: myEventListener,
    touchstart: myEventListener
});
Parameters
Name Type Argument Default Description
events Object

events hash or a name/listener pair.

noCustomEvent Boolean <optional>
false

Disable Element.Event custom events.

priority Number <optional>
0

The priority level of the callback listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added.

useCapture Boolean <optional>
false

use capture events instead of bubbling

Returns

the current Element instance.

Type
Element

triggerEvent(eventName) → {Element}

Trigger an event listener on a target.

Notes: It will only trigger events added using Element.add[Event|Events] methods.

Example
// Your existing element
var myElement = UWA.createElement('a', {
        text: 'My Link'
   }),

   myEventListener = function (event) {

        // Stop event propagation and prevent default.
        UWA.Event.stop(event);
   };

// Add a "click" event
myElement.addEvent('click', myClickListener);

// Manualy trigger "click" event listener
myElement.triggerEvent('click');
Parameters
Name Type Description
eventName String

the event name (e.g "click").

Returns
  • the current Element instance.
Type
Element

removeEvent(event, listener, useCapture) → {Element}

Remove event listener(s) on a target.

Event delegation:

As normal events, to remove a target event listener, you have to pass the full event name and selector, plus the listener function. Passing only the event name and selector will remove all events matching this event and selector. Passing only the event name (without selector) will remove all events matching this name regardless of its delegated state.

Example
// Your existing element
var myElement = UWA.createElement('a', {
        text: 'My Link'
   }),

   myEventListener = function (event) {

        // Stop event propagation and prevent default.
        UWA.Event.stop(event);
    };

// Add a "click" event
myElement.addEvent('click', myClickListener);

// Remove all "click" events
myElement.removeEvent('click');

// Remove only "click" events associate with "myClickListener" listener
myElement.removeEvent('click', myClickListener);
Parameters
Name Type Argument Default Description
event String

the event name (e.g "click"). If not specified, it will remove all events on this element.

listener Function

the event listener function. If not specified, it will remove all events matching the given event name.

useCapture Boolean <optional>
false

if true, removes the event added with useCapture to true

Returns
  • the current Element instance.
Type
Element

removeEvents(events, useCapture) → {Element}

Remove multiple events listener(s) on a target.

Examples

You can remove all element's attached events at once by calling this method without arguments.

var myElement = UWA.createElement('a', {
    text : 'My link'
}).addEvents({
    'click' : function () {},
    'customEvent' : function () {}
});

// Shouldn't have any event handler left attached
myElement.removeEvents();
Parameters
Name Type Argument Default Description
events Object

events hash or a name/listener pair.

useCapture Boolean <optional>
false

if true, removes the events added with useCapture to true

Returns
  • the current Element instance.
Type
Element

fillParent(property, reference) → {Element}

Fill the parent with the current element. The element will have the maximum place allowed by the parent, and the content of the parent will not overflow it.

Notes: For advanced and internal library usage only.

Parameters
Name Type Description
property String

height or width, defaults to height.

reference Element

by default the element parent node.

Returns
  • the current Element instance.
Type
Element

setSelectable(Boolean) → {Element}

Disable or enable the text selection on the element.

Parameters
Name Type Description
Boolean selectable

define if the text selection should be enabled (true) or disabled (false).

Returns

the current Element instance.

Type
Element

requestFullscreen() → {Element}

Asynchronously requests that the element be made full-screen.

Returns

the current Element instance.

Type
Element