Element object

Element object

Represents DOM element. Element has sub-objects: attributes and styles.

The Element class is derived from the Node class.

Constants

STATE_LINK
STATE_HOVER
STATE_ACTIVE
STATE_FOCUS
STATE_VISITED
STATE_CURRENT
STATE_CHECKED
STATE_DISABLED
STATE_READONLY
STATE_EXPANDED
STATE_COLLAPSED
STATE_INCOMPLETE
STATE_ANIMATING
STATE_FOCUSABLE
STATE_ANCHOR
STATE_POPUP
STATE_OWNS_POPUP
STATE_EMPTY
STATE_BUSY
State flags (bits) of the element, used by get/setState functions. TBD.

Properties

length
rinteger, number of child elements in this element. Read-only property.
[index]
rw – Element, child element of the element at the index position, Read-write index accessor. Zero-based index.
root
rElement, root element of the DOM this element belongs to. Read-only.
view
rView, parent view (window) of the element. Read-only. Note: element.view  may not be equal to global view  variable if the element was moved from one view to another.
parent
r – Element, parent element of given element or null if this element is a root element. Read-only.
layoutParent
r – Element, layout parent element of given element or null if this element is a root element. Read-only.
For positioned elements (position:absolute) layout parent is the positioned container (closest positioned ancestor) element that is used for top/left/bottom/right calculations.
owner
r – Element, owner element of given element or null if this element is a root element. Read-only.
Most of the time the owner is the parent but for popup elements for example owner is the element that owns the popup, e.g. for the tooltip element the owner is the element that causes the tooltip to be shown.
index
r – Integer, index of the element in parent collection. Undefined if this element is not connected to any parent.
tag
rString, tag name of the element. Read-only.
id
r – String, value of attribute id (if any). Read-only.
next
r – Element, next sibling element of the element or null if this is last element in the parent collection.
prior
rElement, previous sibling element of the element or null if this is first element in the parent collection.
first
rElement, first child (element) of the element or null if there are no children.
last
rElement, last child (element) of the element or null if there are no children.
attributes
c – Attributes, collection of html attributes of the element.
@
c – short form to access Attributes, collection of html attributes of the element. It is just an alias of the attributes above.
Sample:
this.@["selected"] = true // or
this.@#selected = true
is an equivalent of
this.attributes["selected"] = true
style
c – Style, style attributes of the DOM element.
state
c – States, collection of states (runtime flags) of the DOM element.
x
c – Extenders, interface to collection of native behaviors attached to the element:
  • element.x.length – reports number of native behaviors attached to the element;
  • element.x[n] – reports name of n-th native behavior attached to the element.
  • element.x.funcname(….) – call of methods implemented by native behaviors.

Main purpose of this interface is to provide function call mechanism that is using separate namespace.

text
rwString, text of the element. For compound elements this property returns plain-text version of the content
html
rwString, (inner HTML) html source of the content of the element. Text returned (String) will not include head and tail tags of the element. Value to set can be either String or Stream object.
outerHtml
rw – String, (outer HTML) html source of the element. Text returned (String) will include head and tail tags of the element.
Value to set can be either String or Stream object.
value
rw – String by default and if the element has native behavior attached to the element it could be also: integer, boolean, array, etc. For example <input type="radio"> will return true if this radio button has "on" state.

Note: property value(v) can be overriden in a behavior class in script. To access native value in such case use Element.state.value property.

prototype
rw – Either Instance of Behavior or Element class object. Prototype can be set to the element through CSS (prototype:name_of_global_behavior_variable) or using this property.
isVisible
rtrue if element and all its containers are in visible state – no visibility:hidden or display:none defined for them. false – otherwise.
isEnabled
rtrue if element and all its containers are not in :disabled state ( setState(Element.STATE_DISABLED)).
ns
rObject, namespace object of the element. All static functions and classes defined in scripts of current document are members of this [namespace] object.
rows
rinteger, Number of rows in the DOM element, for the <table> element returns number of rows in it, for other returns number of rows with respect of flow CSS property.
columns
rinteger, Number of columns in the DOM element, for the <table> element returns number of columns in it, for other returns number of rocolumns with respect of flow CSS property.
options
rElement, for <select> element returns DOM element – container of options that can be used to populate list of options programmatically.
contentModel
rsymbol, Reports current content model of the element (as it defined in HTML5 spec) as one of:
  • #block-inside – the element can contain block elements (e.g. <div>)
  • #inline-inside – the element can contain inline elements (e.g. <p>).
  • #transparent – the content model of a transparent element is derived from the content model of its parent element (e.g. <a>).
  • #text-only – the element can contain only plain text (e.g. <title>).
  • #table, #table-section and #table-row – <table>, <tbody>, <tfoot>, <thead> and <tr> elements.
selection
rnull | Selection, returns Selection object if the element has behavior (htmlarea or richtext) supporting selection functionality.
firstCaretPos
rnull | bookmark, returns bookmark of first caret position inside the element.
lastCaretPos
rnull | bookmark, returns bookmark of last caret position inside the element.
paintBackground
wnull | function(gfx), assigns background layer painting function. The function gets Graphics object that is used to draw the layer. If the function returns true then default background and borders drawing is suppressed. The background drawing function is drawn before native background drawing.
paintContent
wnull | function(gfx), assigns content layer painting function. The function gets Graphics object that is used to draw the layer. If the function returns true then default content drawing is suppressed. The content drawing function gets invoked before native content drawing.
paintForeground
wnull | function(gfx), assigns foreground layer painting function. The function gets Graphics object that is used to draw the layer. If the function returns true then default foreground drawing is suppressed. The content drawing function gets invoked before native foreground drawing.
paintOutline
wnull | function(gfx), assigns outline layer painting function. The function gets Graphics object that is used to draw the layer. If the function returns true then default outline drawing is suppressed. The outline drawing function gets invoked before native outline drawing.
isPointInside
r/w – null | function(x,y), assigns hit tester function. The function gets x,y coordinate and returns true if the point is inside the element shape. This allows to support elements with arbitrary shape.

properties inherited from Node class or Node specific properties

nodeIndex
r – Integer, index of the node in parent nodes collection.
nextNode
r – Element or Node, next sibling node of the node or null if this is the last element in parent collection.
priorNode
rElement or Node, previous sibling node of the node or null if this is the first node in it’s parent’s collection.
firstNode
rElement or Node, reference to first child node (element, text, comment) of the element.
lastNode
rElement or Node, reference to last child node (element, text, comment) of the element.
isElement
rtrue if this node is an element, false – otherwise.
isText
rtrue if the node is a text node.
isComment
rtrue if the node is a comment node.

Enumeration

for … in
for(var child in element) { /* loop body */ } or
for(var (index,child) in element) { /* loop body */ }

Executes body of the loop for each child elements of the element.

Example, for p element in html:
<p>Hello <em>wonderfull</em> world</p>
loop will be executed one time and child variable will get Element("em").

Methods

this
(tagname[, text])

Constructs new Element object with tag equal to tagname (string or symbol). Use it as:

var el = new Element("option"); // or
var el = new Element(#option);

Element will be created in disconnected state. To connect it to the DOM use insert method of the parent element.

create
(object) : Element

Static constructor of DOM elements. object here is an object literal with microformat defined below.

Example, following fragment is an equivalent of creating element with the markup <p>before <button>Hi!</button> after</p>:

var para = Element.create { p, "paragraph text" }; // or if text is a variable:
var para = Element.create { p, [paragraphText] };
clear
() : undefined

Clears a content of the element, removing all its children.

toString
() : string

Returns string – html representation of the element. Text returned is outer html – includes head and tail tags and content s equal to text returned by В html attribute.

clone
() :Element

Returns new copy of the element. Method performs a deep copy of the element. New element is disconnected from the DOM state. Use insert() method to include it in the DOM.

select
(CSSselector:string [, argument1 [, argument2, … ]]) : Element

Returns first element satisfying CSS selector (CSSselector, string). CSSSelector may contain format specifiers like %d, %s which will be substituted by values of argument1argumentN in final CSS selector string. Function uses the same rules as does Stream.printf function.

Example, if document contains <input type="text"/> element then following statement

var inp = self.select("input[type='text']");

will set inp by reference to such element.

$
( CSSselector ) : Element

Returns first element satisfying CSS selector.

Note: this is a "stringizer" method so CSS selector can В be written without "" quotes.

Example, if document contains <input type="text"/> elements then following statement

var inp = self.$( input[type='text'] );

will set inp by reference to such element.

And the following fragment:

var n = 3;
var li3 = self.$( ul > li:nth-child({n}) );

will find third list item in ul list element.

select
(func , CSSselector: string [, argument1 [, argument2, … ]]) returns: integer

Calls func (function reference) for each element satisfying (matching) CSSselector. Function func shall accept one parameter where select will provide reference to matched element. Function may return true to stop enumeration.

Example, following fragment will print out names of all input elements in the document:
function printel(el) { В stdout.println( el.attributes["name"] ); В }
document.select(printel, "input");

selectAll
(CSSselector: string [, argument1 [, argument2, … ]]) returns: Array

Returns array of elements satisfying CSS selector (CSSselector, string). CSSSelector may contain format specifiers like %d, %s which will be substituted by values of argument1argumentN in final CSS selector string. Function uses the same rules as does Stream.printf function.

$$
( CSSselector ) returns: Array

Returns array of elements satisfying CSS selector (CSSselector, string).

Note: this is a stringizer method – the CSSselector provided literally.

selectParent
(CSSselector: string [, argument1 [, argument2, … ]]) returns: Element

Returns first element in child/parent chain satisfying CSS selector (CSSselector, string). CSSSelector may contain format specifiers like %d, %s which will be substituted by values of argument1argumentN in final CSS selector string. Function uses the same rules as does Stream.printf function.

ATTN: Function also inspects this element.

$p
( CSSselector ) returns: Element

Returns first element in child/parent chain satisfying CSS selector.

Note 1: this is a stringizer method – the CSSselector provided literally.

Note 2: Function also inspects this element.

selectParent
(func , CSSselector: string [, argument1 [, argument2, … ]]) returns: integer

Calls func (function reference) for each element satisfying (matching) CSSselector. Function func shall accept one parameter where select will provide reference to matched element. Function may return true to stop enumeration.

Example, following fragment will print out ids of all parent divs of some element:

function printel(el) {  stdout.println( el.attributes["id"] );  }
some.selectParent(printel, "div");

Note: Function also inspects this element.

$$p
( CSSselector ) returns: Array of Elements

Returns array of references of elements in child/parent chain satisfying CSS selector.

Note 1: this is a stringizer method – the CSSselector provided literally.

Note 2: Function also inspects this element.

match
( CSSselector: string [, argument1 [, argument2, … ]]) returns: true | false

Checks if this DOM element satisfies given CSSselector.

$is
( CSSselector ) returns: true | false

Checks if this DOM element satisfies given CSSselector.

Note: this is a stringizer method – the CSSselector provided literally.

belongsTo
( parent: Element [, useUITree: true | false [, includingThis: true | false ]] ) : true | false

Returns true if this element is has parent in its ancestor chain. If useUITree is provided and it is true then the function uses UI relationship rather than strict DOM parent/children relation. For example popup element can be declared outside of its host element but this function returns true for the popup if it was created for this element.

If includingThis is defined and is true then this function returns true for the element itself too : el.belongsTo(el,false,true) -> true. By default includingThis is false.

find
(x, y) returns: Element.

Returns reference to the child of the given element at x,y coordinates relative to the origin of the element. If there is no such element method returns element itself.

update
([deep]) returns: undefined

Remeasures given element (if deep == true) and invalidates its visual area after modifications. Use deep=true value if element will get new dimensions due to some operations on it. Omit deep parameter (or set it to false) if only decoration attributes (not changing dimensions, like color) were changed.

update
(stateUpdateFunction) returns: undefined

That is "transactioned update". The stateUpdateFunction is called with this variable set to the element object and is expected to contain code that modifies state of the element, its content or states of its subelements.

"transactioned update" mechanism is used when the element is expected to have "content" transitions defined in CSS as transition:blend(), scroll-***(), slide-***(), etc.

The Element.update(stateUpdateFunction) does these steps:

  1. Makes snapshot of intial state of the element;
  2. Calls provided stateUpdateFunction() function that is expected to make all needed changes for the new state of the element;
  3. Makes final state snapshot;
  4. Starts the transitioning animation (if it is defined in CSS for the element) using these two snapshots.

If there is no CSS transition defined for the element then stateUpdateFunction() is called and view is updated to the new state of the element immediately.

refresh
( [x, y, width, height] ) returns: true|false

Invalidates area occupied by the element on the screen. If x , y, width, height (coordinates of area inside element) are provided then it invalidates only that portion. This method is useful if you are using Graphics for rendering on element surface area.

animate
( nextStep: function [, whenEnded: function] [, duration: diration | integer] ) : undefined

Starts animation on the element. nextStep is a function that executes animation step (changes dimension, opacity, etc.). This function is called with this set to the element itself and should return integer – number of milliseconds for the next step. If it returns zero or not an integer then animation stops.

If whenEnded function is provided it will be called on the end of the animation.

The duration is a duration of the animation in milliseconds. If it is provided then signature of the nextStep function is expected to be:
function nextStep(progress: float) {}
where progress is a float number from 0.0 to 1.0 – progress of the animation. The nextStep function will always receive progress == 1.0 as the very last step.

box
( part [, edge [, relativeTo ]] ) returns: integer, device pixels

Returns coordinates of the edges of the element. Parameters:

  • part – one of symbolic constants #left, #top, #right, #bottom, #width or #height. Defines part of box (rectangle) to return.
    • If part is #rect then the function returns four values – left, top, right, bottom. Use it for example as
      var (x1,y1,x2,y2) = this.box(#rect, #inner, #view)
      ;
    • If part is #rectw then the function returns four values – left, top, width and height. Use it for example as
      var (x,y,w,h) = this.box(#rectw, #inner, #view)
      ;
    • If part is #dimension the function returns two values – width and height. Use it as:
      var (w,h) = this.box(#dimension, #inner)
      ;
    • If part is #position the function returns two values – left and top. Use it as:
      var (x,y) = this.box(#position, #inner, #view)
      ;
  • edge, one of edges of element:
    • #margin – margin box edge,
    • #border – border box edge,
    • #padding – padding box edge,
    • #inner, default value – inner box edge,
    • #content – content box edge. Content box here is outline of the content of the element and this is not В an inner box of the element. E.g. content box can be bigger than inner box if the element has overflow attribute set.
    • #client – client area, that is #inner box minus areas taken by [optional] scrollbars.
    • #icon -area covered by element’s icon. Icon here is element’s foreground image with foreground-repeat: no-repeat. If element has no such image the function returns #width and #height equals to zero.
  • relativeTo, one of:
    • #screen – returns coordinate relative to the origin of the screen,
    • #root – returns coordinate relative to the origin of root element (view),
    • #parent – returns coordinate relative to the origin of its parent element. Note: parent scroll position relative.
    • #content – returns coordinate of the element in content of its parent. Note: is not dependent on parent scroll position.
    • #container – returns coordinate of the element relative to layout parent. Layout parent can be different from DOM parent element. E.g. position:absolute elements may have positioning layout parent different from DOM parent.
    • #self, default value – all coordinates are relative to the origin of inner box of the element.
    • #view – returns coordinate relative to the origin of the sciter window (view object).
    • or if relativeTo equals one of the following values:
      • #margin – margin box edge,
      • #border – border box edge,
      • #padding – padding box edge,
      • #inner – inner box edge
      • the function will return cumulative widths of correspondent parts, examples:

        var (mx1,my1,mx2,my2) = this.box(#rect, #margin, #inner);
        Each mx* value here will get sum of margin, border and padding in the left, top, right and bottom directions. In other words this call will return distances of margin box from inner(content) box of the element. And this call var (mx1,my1,mx2,my2) = this.box(#rect, #margin, #border); will just return computed values of margin-left, margin-top, margin-right and margin-bottom CSS attributes.

For more information see the CSS box model specification: http://www.w3.org/TR/CSS2/box.html

intrinsicWidthMin
( ) : integer, device pixels

returns min-intrinsic width of the element. min-intrinsic width is minimal width needed to show element without horizontal scrollbar.

intrinsicWidthMax
( ) : integer, device pixels

returns max-intrinsic width of the element. max-intrinsic width is minimal width needed to show element without wrapping, e.g. for the <p> element this will be width of its text replaced in single line.

intrinsicHeight
( forWidth: integer ) : integer, device pixels

returns min-intrinsic height of the element for the given forWidth. min-intrinsic heigh is minimal height needed to show element without vertical scrollbar.

toPixels
( length : length | string | symbol [, #width | #height ] ) : integer, device pixels

returns the length value converted to the number of device pixels. Conversion is made in context of current element style so el.toPixels( em(1.4) ) will number of pixel correspond to 1.4em that us dependent on current font size of the element.

length is a string or symbol then this string is treated as a CSS length literal so it is possible to get values like: el.toPixels(#xx-small) В or el.toPixels(#system-scrollbar-width),

Second symbol parameter is used with the conversion from perecentage lengths:
var h50p = el.toPixels( pr(50.0), #height ); – will calculate the same value as the following CSS declaration: height:50%.

scroll
(part) returns: integer, device pixels

Returns various scrolling related positions of the element. Parameters:

part – one of symbolic constants:

  • #left – left position of the view relative to content origin,
  • #top – top position,
  • #right – offset of right edge of the view from right edge of В the content box,
  • #bottom – offset of bottom edge of the view from bottom edge of the content box,
  • #width – width of scrollable area,
  • #height – height of scrollable area.
  • #rect – returns left,top,right,bottom positions as four integers.
scrollTo
( x:int, y:int [, smooth:bool [, unrestricted : bool] ]  ) : void

Sets scroll position of the element to x,y position. The element should have overflow: hidden-scroll, scroll or auto to be able to scroll its content. If unrestricted is set to true then scroll poistion is allowed to be out of content boundaries.

scrollToView
( [toTop:bool, smooth: bool = true ] )

Scrolls the element to the view – ensures that element is visible. В If toTop is true then forces element to be on top of its scrollable container. This method does deep scroll – it tries to make the element visible through all its scrollable containers. If smooth is false then no attempt to animate the scrolling will be made.

NOTE: in order that method to work the element should establish a box – to be of display: block | inline-block | table-cell | etc. In contrary <tr> (table row) for example is not a box element. In order to scroll to particular row in table you should choose first cell in that row.

mapLocalToView
(xLocal:int, yLocal:int ) : (int,int)

maps xLocal/yLocal point of the element to xView/yView (window) coordinates with respect of CSS tranformations.

mapViewToLocal
(xView:int, yView:int ) : (int,int)

maps xView/yViewl point of the view into xLocal/yLocal (element) coordinates with respect of CSS tranformations.

insert
( element | html | object | array [,index = Integer.MAX]) returns: true | false.

element is a child DOM element (instance of this Element class) to be inserted at the index position. If index is greater than current number of children in this element then new element will be appended as a last element. Index is optional parameter, if ommited then element will be appended to collection. If element is already a child of some other parent then it will be disconnected from it automaticly.

If first parameter is string (html text) then attempt will be made to insert it at given position.

If first parameter is an object then it is considered as a template for creation of new DOM element. Microformat of that object is defined below.

If first parameter is an array it shall contain DOM Node references (elements and/or text nodes).  

append
( element | html | object | array ) returns: true | false.

Equivalent of insert ( ... , Integer.MAX );

prepend
( element | html | object | array ) returns: true | false.

Equivalent of insert ( ... , 0 );

content
( element | array [, element2 [, element3, … ]] ) returns: true | false.

Replaces content of the element by elements, that is short form of el.clear(); el.append(element1); el.append(element2); …

This method can be used for setting cells in <tr>s. It handles properly cells with col/rowspans.

For all other elements elementN can be either DOM element, string, object ( template of the element that uses microformat ) or array of Elements/Nodes.

$content
( .. inline html .. ) : Element

Stringizer method, replaces content of the element by the inline html. As this is a stringizer method then html can be provided as it is, example:

var el = ... , num = ...;
el.$content(This is item number { num });

Method returns the element itself.

$append
( .. html .. ) : Element

Stringizer method, adds content defined by the inline html to the end of the list of children of the element.

Method returns first added element.

$prepend
( .. html .. ) : Element

Stringizer method, insert content defined by the inline html at the start of children list of the element.

Method returns first added element.

$after
( .. html .. ) : Element

Stringizer method, adds content defined by the inline html to the parent of the element immediately after this one.

Method returns first added element.

$before
( .. html .. ) : Element

Stringizer method, insert content defined by the inline html to the parent of the element immediately before this one.

Method returns last added element (that will be new this.prior element).

$replace
( .. html .. ) : Element

Stringizer method, removes this element from the DOM and content defined by the html in its place.

Method returns first added element.

detach
( ) : В Element

Removes this element from its parent’s children collection so after call of this method this.parent become null. If update is true then calls update() for the parent element. Returns element that was just detached (this). This method does not destroy state and behaviors attached to the element until GC will not collect the element (if there are no references to it)

remove
( ) : В Element

Removes this element from its parent’s children collection so after call of this method this.parent become null. If update is true then calls update() for the parent element. Returns element that was just detached (this). All runtime states and behaviors are destroyed by the method. Native behaviors will receive BEHAVIOR_DETACHED event.

load
( url: string[, headers: object] ) returns: true/false

Loads content of the document referred by url as a content of this element. For elements having behavior:frame assigned it loads html, styles and executes scripts refered by the url or contained in the stream. Upon completion of loading behavior:frame posts DOCUMENT_COMPLETE event. For any other elements it loads only content of body portion of the document, no style loading or script execution happens in this case. If the url points on external resource like "http://…" then the method is asynchronous. Otherwise it tries to load the resource synchronously.

If headers object ( name/value map) is present and url is http/https then HTTP GET request is sent with those headers.

load
( stream: Stream ) returns: true/false

Loads content of the document from in-memory stream as a content of this element. For elements having behavior:frame assigned it loads html, styles and executes scripts refered by the url or contained in the stream. For any other elements it loads only content of body portion of the document, no style loading or script execution happens in this case.

load
( html: string, url:string ) returns: true/false

Loads the html document from string as a content of this element. For elements having behavior:frame assigned it loads html, styles and executes scripts refered by the the html content. For any other elements it loads only content of body portion of the document, no style loading or script execution happens in this case.

loadImage
( url: string [, callback: function [, useCache: true|false ] ]  ) returns: Image | null

Loads image from the url. If callback is ommited then the engine will try to load image sycnhronously otherwise (if callback is a function) engine will issue asynchronous request and will call this function upon arrival.

If useCache is not false then the method will try to use image cache to get the image and on successful download the image will go to the cache too. By default useCache is false.

Signature of the callback function is function callback(image, status) where image is an object of class Image or null in case of error, status is http status (200,404,etc).

bindImage
( url: string , img: Image ) returns: true | false

Binds the img with the URL. As a result the image can be used in CSS for example as a background. URL can be any arbitrary unique string here, like "in-memory:dyn-image1".

bindImage
( url: string ) returns: Image | null

Returns image that was previously bound with the URL or null if there is no such image.

request
( callback: function | integer, #get | #post | #post-data | #put-data | #post-json | #put-json | #delete, url: string [, params: object [, headers: object] ] ) : Object | Stream | Bytes | Error

Sends synchronous or asynchronous http data GET/POST request to the server/page (url), a.k.a. JSON-RPC calls.

  • #get, #post, #post-data #json are literal symbols – type of http request to be sent:
    • #get – sends plain HTTP GET request, url-encoded params (if any) are appended to the url to form the request;
    • #post – sends HTTP POST request with params serialized as Content-Type: application/x-www-form-urlencoded;charset=utf-8;
    • #post-data – sends HTTP POST request with params serialized as Content-Type: multipart/form-data; boundary= ...;
    • #put-data – sends HTTP PUT request with params serialized as Content-Type: multipart/form-data; boundary= ...;
    • #post-json – sends HTTP POST request with params serialized as JSON, В Content-Type: application/json;charset=utf-8;
    • #put-json – sends HTTP PUT request with params serialized as JSON, Content-Type: application/json;charset=utf-8;
    • #delete – – sends HTTP DELETE request.
  • url is a string – url of the page (location) on the server handling HTTP requests.
  • params is an object, its properties are serving role of parameters of HTTP request.
  • headers is an object – a map of additional header key/value pairs to send along with the request.
  • returns: true|false for asynchronous requests or pair of (status:integer,data:any) – result of the request (see data below) and HTTP status code (e.g. 200 – OK, 404 – resource was not found on the server).
If parameter callback is an integer than it is treated as a timeout value (number of milliseconds) and the function executes synchronous request. If the callback is a function then response from the server will be delivered by calling the callback function having following signature:
function dataArrivedCallback( data: any, status: integer );

where data is either one of:

  • instanceof Error object, in case of data response parsing problems;
  • stream, if data returned by the server is of textual type (text/plain, text/html, text/xml, etc.)
  • instanceof Object, Array, etc. if response has content type text/javascript, text/ecmascript, text/tiscript or application/json and was successfully parsed into data object.
  • Bytes, if data returned by the server is of binary type (image/*, etc.). Bytes.type in this case will contain a string – mime-type of the data reported by the server.

and status code is an integer – HTTP status code (e.g. 200 – OK, 404 – resource was not found on the server) or if code is greater than 12000 it is a WinInet error code, see: http://support.microsoft.com/kb/193625.

Example of server data response (type: text/javascript) :

({ id : 1234, message : "Hello from XYS server!" })

– in this case server returns object having two properties: id and message. Rationale behind of ({ and }) was explained here.

getState
( [stateFlags:int] ) :int

Returns state of the element. stateFlags here is a set of bits – "ORed" constants STATE_***. stateFlags is provided then function returns int – flags of the element ANDed with the provided stateFlags variable. If no stateFlags is given then the function returns full set of flags element has at hte moment.

setState
( stateFlags:int) :void

Function will set flags to the element update document on the screen accordingly (resolve styles and refresh).

clearState
( stateFlags:int ) :void

Function will clear flags of the element and update document on the screen.

capture
( onOff: true | false | #strict ) :void
  • element.capture(true) – sets "soft" mouse capture to the element, mouse messages are delivered to the element and its children;
  • element.capture(#strict) – sets "strict" mouse capture to the element, mouse messages are delivered to the element only;
  • element.capture(false) – removes mouse capture from the element.
popup
( el: Element [, placement: int] ) :void

Function will show element el as a popup window placed relatively to this element. Placement is a combination of two values from two groups:

Point on this element ( a.k.a. popup anchor point )

  • 1 – this element’s bottom-left point
  • 2 – this element’s bottom-center point
  • 3 – this element’s bottom-right point
  • 4 – this element’s center-left point
  • 5 – this element’s middle-center point
  • 6 – this element’s middle-right point
  • 7 – this element’s top-left point
  • 8 – this element’s top-center point
  • 9 – this element’s top-right point

Point on popup to be placed at the anchor point:

  • 1 << 16 – popup bottom-left is at anchor point
  • 2 << 16 – popup bottom-center is at anchor point
  • 3 << 16 – popup bottom-right is at anchor point
  • 4 << 16 – popup center-left is at anchor point
  • 5 << 16 – popup middle-center is at anchor point
  • 6 << 16 – popup middle-right is at anchor point
  • 7 << 16 – popup top-left is at anchor point
  • 8 << 16 – popup top-center is at anchor point
  • 9 << 16 – popup top-right is at anchor point
( see keyboard numpad to get an idea of numbering).

placement parameter is optional. The popup position can also be defined in CSS  by popup-position property.

popup
( el: Element, x:int, y:int ) :void

Function will show element el as a popup window placed at x, y (view relative coordinates). Placement is ‘7’.

( see keyboard numpad to get an idea of numbering).
closePopup
() :void

Function will close popup if element el or any of its parent is a popup window.

timer
( milliseconds: integer, callback: function [, avoidSameOriginCheck : bool ] )

If milliseconds is greater than zero the method will create timer for the DOM element with milliseconds delay.

After milliseconds delay engine will call callback function with this variable set to the dom element. Return true from the callback() function if you need to continue timer ticks and false otherwise.

Call of timer() with milliseconds = 0 parameter will stop the timer.

If the element already contains running timer with function of the same oringin as the callback then that timer gets removed before adding new timer. Passing true as avoidSameOriginCheck parameter will suppress same origin matching.

swap
(other: Element ) : null

Swaps DOM positions of two elements – owner of the method and the other. Returns element whose method is called.

sendEvent
( eventCode:int [, reason: int [, owner: Element | null [, data:value ]]] ) : true | false | value

traverse (send) bubbling event to the parent/child chain of this element. Events generated by this method can be handled by onControlEvent() methods of elements in the chain.

  • eventCode is either one of constants from Logical event codes from builtin behaviors ( see: Event ) or any integer value above 0x1000 (custom control events range).
  • reason here is an arbitrary integer value that sender and receiver knows about.
  • owner is an optional reference to some DOM element. E.g. in MENU_ITEM_CLICK this is a reference to element – owner of popup menu or null.
  • data is any json value that will passed to BEHAVIOR_EVENT_PARAMS.data field (see: sdk/api/sciter-x-behavior.h file)
The sendEvent does traversal so it returns true if the event was consumed – one of onControlEvent() handlers in parent/child chain returned true while handling this event. If some element in child-parent chain consumes the event (returns true) and sets the data field the value of this updated data field will be returned from the sendEvent() function.
sendEvent
( event:string [, data:value ] ) : true | false | value

traverse (send) bubbling event to the parent/child chain of this element. Events generated by this method can be handled by onControlEvent() methods of elements in the chain.

  • event is an event name possibly with namespace, see Element.subscribe/unsubscribe() below.
  • data is any json value that will passed to BEHAVIOR_EVENT_PARAMS.data field (see: sdk/api/sciter-x-behavior.h file). The data is also available as evt.data field in event handlers.
The sendEvent does traversal so it returns true if the event was consumed – one of handlers in parent/child chain returned true while handling this event. If some element in child-parent chain consumes the event (returns true) and sets the data field the value of this updated data field will be returned from the sendEvent() function.
postEvent
( event:string [, data:value ] ) : true

The postEvent places event into the internal queue of posted events for future traversal by sendEvent(name,data) and returns immediately.

postEvent
( eventCode:int [, reason: int [, owner: Element | null [, data:value ]]] ) : undefined

The postEvent places event into the internal queue of posted events for future traversal by sendEvent and returns immediately.

sendKeyEvent
( eventDef: object ) : true | false | undefined

The sendKeyEvent simulates the key event. eventDef may have following fields:

{
  type: Event.KEY_DOWN or Event.KEY_UP or Event.KEY_CHAR; // type if key event
  keyCode: int; // Key or char code, e.g. 'O'
  altKey: true or false; // optional, 'ALT' key pressed flag
  shiftKey: true or false; // optional, 'SHIFT' key pressed flag
  ctrlKey: true or false; // optional, 'CTRL' key pressed flag
  shortcutKey: true or false; // optional, 'CTRL/win' or 'COMMAND/mac' key pressed flag
  commandKey: true or false; // optional, 'WIN/win' or 'COMMAND/mac' key pressed flag
}

Function returns true if the event was consumed during sinking/bubbling dispatching of the event using this element as a target.

sendMouseEvent
( eventDef: object ) : true | false | undefined

The sendMouseEvent simulates the mouse event. eventDef may have following fields:

{
  type: Event.KEY_DOWN or Event.KEY_UP or Event.KEY_CHAR, // type if key event
  altKey: true or false, // optional, 'ALT' key pressed flag
  shiftKey: true or false, // optional, 'SHIFT' key pressed flag
  ctrlKey: true or false, // optional, 'CTRL' key pressed flag
  shortcutKey: true or false; // optional, 'CTRL/win' or 'COMMAND/mac' key pressed flag
  commandKey: true or false; // optional, 'win/win' or 'COMMAND/mac' key pressed flag
  mainButton: true or false, // optional, left mouse button pressed flag
  propButton: true or false, // optional, right mouse button pressed flag
  x: int, // x mouse coordinate, view relative
  y: int, // y mouse coordinate, view relative
}

Function returns true if the event was consumed during sinking/bubbling dispatching of the event using this element as a target.

post
( callback: function [,only_if_not_there:boolean] ) : undefined

This method allows to delay execution of callback function. While calling the callback function engine will set this environment variable to the element this post call was invoked with.

Optional parameter only_if_not_there if defined and is true allows to post delayed event only once. Multiple post with the same callback function will yield to a single entry in posted events queue.

url
( [ relativeUrl: string ] ) : string

Method builds absolute url from the relativeUrl by using document url as a base. В If there is no relativeUrl then the method just returns url of the document this DOM element belongs to.

sort
( comparator: function [, fromIndex: integer [, numOfElements:integer]] В ) : void

Sorts children of the element by using comparator function. comparator function has to have following signature:

function cmp(el1: Element, el2: Element) : int

that returns negative int value if el1 is less than el2, 0 if they are equal and positive value if el1 is greater than el2.

fromIndex and numOfElements are used for defining range of elements to sort.

move
( [x: int, y: int [, w: int, h: int] [, relto] [, mode ][, referencePoint: int]  ) : void

This methods transforms the element into the "sprite" – element that moves independently from the rest of the DOM:

Declares element as having position:popup and moves it to the position (x,y). If the element happens to be outside of the view then engine creates special popup window for it. Third parameter describes role of x and y values. w and h parameters, if provided, change dimensions of the element.
mode parameter

  • #auto – window is created if element is moved outside of the view. If element stays inside the view it is rendered as popup:fixed.
  • #attached-window – forces the engine to create popup window for the element, window is moved in sync with its host window (view).
  • #detached-window – forces the engine to create popup window for the element, element’s window position is indpenedent from the host window.
  • #detached-topmost-window – that is #detached-window but created on topmost window layer.

relto tells what kind of coordinates x,y are: #view, #root, #screen or #self relative. Default – #view.

referencePoint is a number from 1 to 9 – defines what x,y are cordinates of. 7 is top/left corner, 5 is center of the element, see numpad on keyboard. NOTE: if provided the referencePoint defines position of element’s border box.  In all other cases x/y defines position of top/left corner of cotent box.

Samples are in sdk/samples/ideas/moveable-windows/ and sdk/samples/ideas/rect-tracker/ folders.

Call of the move() without parameters restores default positioning of the element.

See also: Element.style.dimension() method.

textWidth
( text: string ) : int

Calculates width of the text with respect of current font defined for the element. If text contains multiple lines separated by "\n" character then it returns width of widest string.

textHeight
( text: string ) : int

Calculates height of the text with respect of current font and line-height defined for the element. If text contains multiple lines separated by "\n" character then it returns sum of heights of all strings.

subscribe
( handler: function, eventGroup : int [, eventType: int] ) : <this element>

Assigns the handler function to the particular event that may occur on this particular DOM object.

handler function should have following signature function(evt) {…}, where evt is an Event object that describes the event in details.

eventGroup here is one of the following constants:

  • Event.MOUSE – group of mouse events (like Event.MOUSE_DOWN, Event.MOUSE_UP, etc. );
  • Event.KEY – group of keyboard events (like Event.KEY_DOWN, Event.KEY_UP, etc. );
  • Event.BEHAVIOR_EVENT – group of generated, synthetic events (a.k.a. control events like Event.BUTTON_CLICK, Event.HYPERLINK_CLICK, Event.BUTTON_STATE_CHANGED, etc. );
  • Event.FOCUS – group of scroll events;
  • Event.SCROLL – group of scroll events;
  • Event.SIZE – size changed event;

eventType here is one of constants defined below for particular group of event. eventType parameter is optional – if it is not provided then the handler function will receive all events of the eventGroup.

subscribe() method allows to attach multiple and independent event handling functions to single element.

Note that subscribe() is not a substitution of onMouse(evt), onKey(evt), etc. event handlers defined below. These two ways of handling events work side-by-side. onXXXX() methods are used for defining event handlers in classes (Behaviors) so to handle events for classes of elements. And subscribe()/unsubscribe() are used for attaching event handlers to particular elements.

Method returns the element it was called for. This allows to chain subscribe() calls.

subscribe
( event: string [, selector: string] , handler: function ) : <this element>

Assigns the handler function to the particular event that may occur on this DOM object or on one of its children. The event here is a string that can accept symbolic event names.

Event names may have namespaces in their names. For example: "click.mywidget" defines click handler assigned by some mywidget component. Namespaces are especially useful when you need to unsubscribe multiple handlers at once. For example this el.unsubscribe(".mywidget") will remove all handlers with mywidget namespace.

The selector is an optional parameter – CSS selector of child element. When provided allows containers to subscribe to events coming from particular children.

The handler can be any function(evt:Event) {...} – callback that gets invoked when the event occurs. this variable is set to the evt.target – element that originated the event.

To subscribe on event in EVENT_SINKING phase prepend the event name by ~ symbol. For example this handler
container.subscribe("~keydown", function() {...});
will receive the keydown event before its children.

Note: this method mimics jQuery’s .on() method and has the same semantics.

on
( event: string [, selector: string] , handler: function ) : <this element>

Alias of subscribe(event: string [, selector: string] , handler: function) above.

unsubscribe
(handler: function ) or
(eventGroup : int [, eventType: int]) : <this element>

unsubscribe() method detaches event handler[s] from the element.

unsubscribe
(event : string [, selector: string]) : <this element>

The method detaches matching event handlers from the element that were set previously by subscribe("name",…) method.
Example:
  el.unsubscribe("click");
will remove all event handlers with "click" name. Even those that have also namespace defined like "click.mywidget".

Note: this method mimics jQuery’s .off() method.

off
alias of unsubscribe methods above.
commonParent
(other : Element) : Element

The method returns common parent element of this and other DOM elements.

row
(rowNo: integer) : array of Elements

The function returns list (array) of elements that were replaced in given row.

column
(colNo: integer) : array of Elements

The function returns list (array) of elements that were replaced in given column.

rowY
(rowNo: integer) : (y: integer, height: integer)

The function returns position and height of the row.

columnX
(colNo: integer) : (x: integer, width: integer)

The function returns position and width of the column.

transact
( action:function [, name:string] ) : true | false

The transact method executes so called editing transaction – group of operations that can undone/redone as a whole. The action function should have this signature:

function action(transaction) { ... }

Where the transaction is an instance of the Transaction interface – primitives used to modify state of the DOM. Any modification made through these function will be undone/redone properly when user will issue Undo/Redo commands in the editor.

execCommand
( command:string [, attributes:map] ) : true | false

The execCommand method executes undoable editing command. The command string identifies command to execute.

Editing commands common to all editable elements ( <input|text>, <textarea>, <plaintext>, <htmlarea> ):

  • "edit:cut" – cut selection – copy selection to the clipboard and remove it;
  • "edit:copy" – copy selection to the clipboard;
  • "edit:paste" – paste content of the clipboard;
  • "edit:selectall" – select whole content of the element;
  • "edit:undo" – undo last editing operation;
  • "edit:redo" – redo last operation that was undone;
  • "edit:delete-next" – if there is a selection – delete selected content, otherwise delete next character;
  • "edit:delete-prev" – if there is a selection – delete selected content, otherwise delete previous character;
  • "edit:delete-word-next" – if there is a selection – delete selected content, otherwise delete next word;
  • "edit:delete-word-prev" – if there is a selection – delete selected content, otherwise delete previous word;

Editing commands supported by behavior richtext elements ( <htmlarea> ):

  • "edit:insert-break" – essentially this is "ENTER" (VK_RETURN) command, actual DOM modification depends on context;
  • "edit:insert-soft-break" – "SHIFT+ENTER" command, inserts <br> separator but actual DOM modification depends on context;
  • "format:apply-span:{tag-list}" – wrap selection into span element, if the selection contains one of tags they will be removed.
    • {tag-list} is a pipe (|)  separated list of tag names. Example:
      execCommand("format:apply-span:b|strong") – will wrap selection into <b>...</b> while removing any other <b> and <strong> elements from the selection.
    • Additional map parameter may contain list of DOM attributes to add to wrapping element, Example:
      execCommand("format:apply-span:font",{color:"#F00"}) – will wrap selection into <font color="#F00">...</font> element.
  • "format:toggle-span:{tag-list}" – if selection contains one of the tags – removes them, otherwise it does "format:apply-span:..." action.
  • "format:toggle-list:{list-tag}" – converts paragraphs in selection into a list. If selection is already a list of that type then items of the list will be converted tp simple paragraphs;
    • {list-tag} can be either ul, ol or dl.
  • "format:toggle-pre" – converts selection to or from <pre> block.
  • "format:indent" –  wraps selected paragraphs into <blockquote> or sub-list.
  • "format:unindent" –  unwraps selected paragraphs from <blockquote> or moves sub-list to one level up.
  • "format:morph-block:{to-tag}" – changes tags of selected block elements. This way current <blockquote>  can be changed to <div> for example.
queryCommand
( command:string [, attributes:map] ) : integer

The queryCommand method reports state and allowance of particular command. The method accepts the same parameters as the execCommand(). Return value is an integer – combination of the following flags:

  • 0x01 – command is "on" state or "selected". For example, queryCommand("format:apply-span:b|strong") will return 0x01 value if selected text  contains either <b> or <strong> elements.
  • 0x02 – command is "disabled" or is not available in current context.

    Node specific methods

    insertNodeBefore
    ( node: Node)

    Inserts the node in the DOM tree before this element.

    insertNodeAfter
    ( node: Node)

    Inserts the node in the DOM tree after this element.

    appendNode
    ( node: Node)

    Inserts the node after last node of this element so the node becomes last child node of the element.

    prependNode
    ( node: Node)

    Inserts the node before first node of this element so the node becomes first child node of the element.

    Element events

    Sinking/Bubbling events:

    onMouse(event) : true|false

    Event.MOUSE_ENTER
    Mouse/Pointer enters the element.
    Event.MOUSE_LEAVE
    Mouse/Pointer leaves the element.
    Event.MOUSE_MOVE
    Mouse/Pointer moves over the element.
    Event.MOUSE_DOWN
    One of mouse buttons pressed in the element. event.mainButton and event.propButton will tell what button was pressed.
    Event.MOUSE_UP
    One of mouse buttons released in the element. event.mainButton and event.propButton will tell what button was pressed.
    To detect single MOUSE CLICK event use following condition:
    event.type == Event.MOUSE_UP && this.getState(Element.STATE_PRESSED)
    Event.MOUSE_DCLICK
    Double mouse click in the element.
    Event.MOUSE_WHEEL
    Mouse wheel rotation. event.wheelDelta is a number of wheel ticks made.
    Event.MOUSE_TICK
    Repeatable event that is generated when one of mouse button pressed.
    Event.MOUSE_IDLE
    Pulsed event, is generated when mouse is not moving some short period of time. If it is not handled in the code then it is used by the engine to popup tooltip for the element.

    onKey(event) : true|false

    Event.KEY_DOWN
    Keyboard key pressed. event.keyCode is virtual key code of the key.
    Event.KEY_UP
    Keyboard key released. event.keyCode is virtual key code of the key.
    Event.KEY_CHAR
    Character key pressed. event.keyCode is a value of UNICODE codepoint.

    onFocus(event) : true|false

    Event.GOT_FOCUS
    Focusable element got input focus.
    Event.LOST_FOCUS
    Elements lost input focus.

    onControlEvent(event) :true|false

    Synthetic (logical) events:

    Event.BUTTON_CLICK
    Click on button, generated by behaviors: button, checkbox, radio.
    Event.BUTTON_PRESS
    Mouse/Key pressed in button, generated by behaviors: button, checkbox, radio.
    Event.BUTTON_STATE_CHANGED
    State (value) of button was changed, generated by behaviors: checkbox, radio.
    Event.EDIT_VALUE_CHANGING
    Value of editbox is about to be changed, generated by behaviors: edit, number, decimal, date, masked. element.value reflects old value.
    Event.EDIT_VALUE_CHANGED
    Value of editbox was just changed, generated by behaviors: edit, number, decimal, date, masked. element.value reflects new value.
    Event.SELECT_SELECTION_CHANGED
    Selection was changed in elements-selectors. generated by behaviors: select, dropdown-select, calendar.
    Event.SELECT_STATE_CHANGED
    State of item was changed in elements-selectors. generated by behaviors: select when some of the <options> are expanded/collapsed, event.target is the item that changed its state. behavior: calendar sends this event after calendar was switched to show another month so by handling this event you can update DOM inside the calendar. В
    Event.HYPERLINK_CLICK
    Click on hyperlink. event.target is that hyperlink element.
    Event.ACTIVATE_CHILD
    Request to container to activate child. accesskey processor post this message if accesskey is defined for the element but element is passive, e.g. tab on Tabs control. See: extenders.js / type Tabs.
    Event.POPUP_REQUEST
    Secret stuff.
    Event.POPUP_READY
    Event.POPUP_DISMISSED
    Event.MENU_ITEM_ACTIVE
    Happens when menu item is highlighted.
    Event.MENU_ITEM_CLICK
    Click on menu item. event.target is the item event.owner is an owner of the popup menu.
    Event.range 0x1000 .. 0x7FFF
    Custom control events. Any code from this range can be used in element.sendEvent(code,…) calls.
    If behavior class is designed to behave like for example a button then you may use element.postEvent(Event.BUTTON_CLICK,…) to notify all parties about clicks.

    onGesture(event): true|false

    Gestures, DOM events, available on devcices with touch screen support.

    See Gesture (touch screen) event codes in Event object definition.

    onCommand(event): true|false

    Commands, actions to be executed by text editing elements like <textarea>, <input|text>, <htmlarea>, <plaintext>, etc. See: Element.execCommand().

    Event.COMMAND_EXEC
    Execute command: event.command:string is a command to be executed,  event.data – parameters.
    Event.COMMAND_QUERY
    Query state/allowance of command execution.

    Non-bubbling events

    onScroll(event) : true|false

    Event.SCROLL_HOME
    Requests to scroll, typically are coming from <input type=vscrollbar> or <input type=hscrollbar>.
    In case of SCROLL_POS use event.scrollPos field to get requested position to scroll.
    Event.SCROLL_END
    Event.SCROLL_STEP_PLUS
    Event.SCROLL_STEP_MINUS
    Event.SCROLL_PAGE_PLUS
    Event.SCROLL_PAGE_MINUS
    Event.SCROLL_POS

    Behavior specific events

    attached() : void
    Method of behavior class (type). If defined in the type definition then it will be invoked by the engine when DOM element will be subclassed by this class. Variable this inside this function is a reference to the DOM element this behavior was just attached to. Consider attached() as an equivalent of constructor function for other classes.
    onTimer()
    Timer tick. To start timer on the element use element.timer(milliseconds) call. Return false from this method to stop the timer.
    onSize()
    Size of the element was changed. To get dimensions use this.box() function.

    Root specific events

    self.ready()
    Event is generated as a final step of document loading.
    self.closing(reason)
    Document is about to be closed. Event handler can prevent unloading by returning false value. The reason parameter is one of following symbols:
    – #by-chrome – user clicked close button on window;
    – #by-code – view.close() issued;
    – #by-load – document gets unloaded by loading new document.

    Element.create and Element.insert object-template microformat.

    Object-template is an object literal used for generation of new elements. It shall obey following rules:
    {
      div, // mandatory, first property and without value - tag name of the DOM element.
           // E.g. div, p, option, select, etc.
       attr1name : "attr1value", // optional, attribute #1 of created dom element.
       attrNname : "attrNvalue", // optional, attribute #N of created dom element.
       "some text", // optional string, text of the DOM element
                    // if that element is a text container like p, text, span, etc.
      [ object-1, "text", ... object-N ] // optional array of templates - definitions
                                         // of text and child elements of the element.
    }
    

    The "text" and [ children ] definitions are mutually exclusive – either one of them shall be defined or none.

    Example, following script:

     sb.insert
     {
        div, class:"dyn",
         [
          {p, "Text1" },
          {p, ["Text2 before ", {button, "Hi!"}, " after"] }
         ]
     };
    

    Is an equivalent of the following:

    sb.insert(
       ""
       "Text 1"
       "Text 2 before Hi! after"
       ""
    );