---
title: Global functions
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/globals/
updated: 2026-11-18T13:58:14.460Z
---

# Global functions

> The functions and variables that the library adds to the window object.

The library adds these functions and variables to `window`, so they are available everywhere in your code. Start with [Paths](../../guides/paths/) and [Data binding](../../guides/data-binding/) to see how they work together.

## API

### ADAPT(path, id, text)

Type: `method`

Prepares a piece of HTML for a specific path and identifier.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The value for `~PATH~` and `CLASS`. Use `null` to skip these replacements. |
| `id` | `String` | yes |  | The value for `~ID~`. Use `null` to skip this replacement. |
| `text` | `String` | yes |  | The text to prepare. |

Returns: `String` The prepared text.

The method translates `@(text)` markup, applies `--name--` variables and replaces `~CDN~` with [DEF.cdn](../def/). When `path` is set, `~PATH~` and `CLASS` become the path, `<ui-plugin>` elements without a `path` attribute receive it, and the first `PLUGIN(function(` becomes `PLUGIN('path', function(`. When `id` is set, `~ID~` becomes the identifier. A `text` that is empty or is not a string is returned unchanged.

Example: Replace the keywords
```js
var html = '<div class="CLASS" data-id="~ID~">~PATH~</div>';
console.log(ADAPT('users', 'u1', html)); // <div class="users" data-id="u1">users</div>
```

### AJAX(url, [data], callback, [onprogress], [scope], [id])

Type: `method`

Sends an HTTP request and delivers the response to a function or a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The method, the address and optional keywords, for example `POST /api/users/ ERROR`. |
| `data` | `Object` | no |  | The request body: an object sent as JSON, a string sent as form data, or `FormData`. |
| `callback` | `Function|String` | yes |  | A function that receives the response, or a path that receives it. |
| `onprogress` | `Function|String` | no |  | A function or a path that receives the upload percentage. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |
| `id` | `String` | no | `url` | The key used by `SYNC` and by the cache. |

The `url` starts with the HTTP method, followed by the address and optional keywords separated by spaces:

| Keyword | Meaning |
| --- | --- |
| `ERROR` | Passes the response through [ERROR()](../globals/). If it holds an error, the `ERROR` event is emitted and `callback` does not run. An error status without a response body emits the `ERROR` event with the status code. |
| `SYNC` | Queues requests with the same `id`, so that they run one after another. |
| `<1 minute>` | Caches the response for the given time with [CACHE()](../globals/), unless it is an error. While the request is pending, other calls with the same `id` wait for its response, so only one request is sent. |
| `#name` | Loads the code list `name` first. See [CL()](../globals/). |
| `@flag` | Emits the flag when the request is sent. See [Flags and path modifiers](../../guides/flags/). |

An object in `data` is sent as JSON, a string is sent as it is with the content type `application/x-www-form-urlencoded`, and `FormData` is sent as a form.

A status code of 400 or higher counts as an error. A request that cannot reach the server, is aborted or runs out of time has the status code `0`, and `callback` receives an empty response. A response with a JSON content type is parsed with [PARSE()](../globals/). Every request adds the headers from [DEF.headers](../def/). When [DEF.language](../def/) is set, it is added to the query string. When [DEF.version](../def/) is set, it is added to the query string of `.html` addresses.

The `request` and `response` [events](../events/) let you inspect or change each call. Once the request is sent, `options.xhr` in the `request` event holds its `XMLHttpRequest`, so `options.xhr.abort()` stops it. `UPLOAD()` is the same function under another name.

Example: Read a response
```js
AJAX('GET /api/users/', function(response) {
	console.log(response.length); // 2
});
```

Example: Store a response in a path
```js
AJAX('POST /api/orders/', { amount: 10 }, 'orders.last');

WATCH('orders.last', function(value) {
	console.log(value.id); // 100
});
```

Example: Send form data
```js
AJAX('POST /api/login/', 'name=Ann&remember=1', function(response) {
	console.log(response.ok); // true
});
```

Example: Stop a request
```js
var request;

ON('request', options => request = options);
ON('ERROR', status => console.log('failed', status)); // failed 0

AJAX('GET /api/report/ ERROR', NOOP);
request.xhr.abort();
```

### API(url, name, [data], callback, [scope])

Type: `method`

Calls a Total.js API endpoint on a specific address.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address of the endpoint. |
| `name` | `String` | yes |  | The name of the operation, optionally followed by keywords. |
| `data` | `Object` | no |  | The data of the operation. |
| `callback` | `Function|String` | yes |  | A function or a path that receives the response. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |

The method sends `POST url` with the JSON body `{ schema: name, data: data }`. Keywords accepted by [AJAX()](../globals/) can follow the name, for example `users_list ERROR`. To use one fixed address, see [TAPI()](../globals/) and [PIPE()](../globals/).

Example: Call an operation
```js
API('/admin/api/', 'users_read', { id: 5 }, function(response) {
	console.log(response.name); // Peter
});
```

### APPEARANCE(options)

Type: `method`

Sets the colour scheme of the page through CSS variables and body classes.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes |  | The switches and the CSS variables. |

Every key becomes a CSS variable on `:root`, except the four switches below. The `color` key also updates [DEF.color](../def/) and adds the variable `--rgb` with the red, green and blue values of a hexadecimal colour with three or six digits.

| Key | Meaning |
| --- | --- |
| `dark` or `darkmode` | Toggles the class `ui-dark` on the body. |
| `large` or `largemode` | Toggles the class `ui-large` on the body. |

The class prefix comes from [DEF.prefixcsslibrary](../def/).

Example: Dark theme with an accent colour
```js
APPEARANCE({ dark: true, color: '#4285F4' });

console.log($('#cssappearance').html()); // :root{--color:#4285F4;--rgb:66,133,244}
console.log($('body').hclass('ui-dark')); // true
```

Example: A short colour
```js
APPEARANCE({ color: '#abc' });

console.log($('#cssappearance').html()); // :root{--color:#abc;--rgb:170,187,204}
```

### ASETTER(name, [a], [b], [c], [d])

Type: `method`

Creates a function that calls a component method later.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The selector and the method, in the same form as in `SETTER()`. |
| `a` | `Object` | no |  | The first argument. |
| `b` | `Object` | no |  | The second argument. |
| `c` | `Object` | no |  | The third argument. |
| `d` | `Object` | no |  | The fourth argument. |

Returns: `Function` A function without arguments.

Each call of the returned function runs [SETTER()](../globals/) with the arguments given here.

Example: Prepare a call
```html
<ui-component name="counter"></ui-component>

<script>
COMPONENT('counter', function(self) {
	self.add = function(value) {
		console.log('added', value); // added 5
	};
});

ON('ready', function() {
	var add = ASETTER('counter/add', 5);
	add();
});
</script>
```

### ATTRD(element, [name])

Type: `method`

Reads a `data-*` attribute from an element or from its closest parent that has it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Event|Element|Object` | yes |  | The starting point. |
| `name` | `String` | no | `id` | The attribute name without the `data-` prefix. |

Returns: `String` The value of the attribute.

The `element` can be a jQuery object, a jQuery event (its `currentTarget` is used) or a DOM element. For a plain object, the method returns the property `name`. Any other value is returned as it is.

Example: Read the closest identifier
```html
<div data-id="15" data-type="user"><button id="save">Save</button></div>

<script>
var button = $('#save');
console.log(ATTRD(button)); // 15
console.log(ATTRD(button, 'type')); // user
console.log(ATTRD({ id: 20 })); // 20
</script>
```

### BLOCKED(key, timeout, [callback])

Type: `method`

Limits how often an operation can run.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The name of the operation. |
| `timeout` | `Number|String` | yes |  | The time in milliseconds, or a text such as `5 minutes`. |
| `callback` | `Function` | no |  | A function that runs when the operation is not blocked. |

Returns: `Boolean` `true` when the operation is blocked.

The first call blocks `key` for the given time and returns `false`. Further calls return `true` until the time passes. A block of 10 seconds or longer is kept in `localStorage`, so it survives a page reload.

Example: Allow one click per second
```js
ON('ready', function() {
	console.log(BLOCKED('save', 1000)); // false
	console.log(BLOCKED('save', 1000)); // true
});
```

### CACHE(key, [value], [expire])

Type: `method`

Reads or writes a value in the persistent cache.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key. |
| `value` | `Object` | no |  | The value to store. |
| `expire` | `String` | no |  | The lifetime of the value, or `session`. |

Returns: `Object` The stored value when reading, otherwise nothing.

With `expire`, the method stores the value. Without it, the method returns the stored value, or `null` when the value is missing or has expired. The value `session` keeps the data in memory until the page is closed. Any other value is a time such as `10 minutes`, `2 hours`, `1 day`, `1 week`, `1 month` or `1 year`, and the data is saved through [DEF.onstoragesave](../def/).

The cache is loaded when the library starts, so use it from the `ready` [event](../events/) onward.

Example: Write and read
```js
ON('ready', function() {
	CACHE('filter', { page: 2 }, '1 day');
	console.log(CACHE('filter')); // {"page":2}
	console.log(CACHE('missing')); // null
});
```

### CACHEPATH(path, expire, [def])

Type: `method`

Keeps the value of a path in the cache between visits.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. |
| `expire` | `String` | yes |  | The lifetime of the saved value, for example `1 day`. |
| `def` | `Object|Function` | no |  | The value used when nothing is saved. A function is called to get it. |

The method saves every change of the path with [CACHE()](../globals/) for the time in `expire`. When the path is empty, the saved value is written to it, and when nothing is saved, `def` is written. A path that already holds a value keeps it.

Called before the library has loaded the cache, the method waits for it and then restores the value. Plugins have the same method with a relative path: [plugin.cachepath()](../plugin/).

Example: Remember a filter
```js
CACHEPATH('filter.q', '1 day', 'all');
console.log(GET('filter.q')); // all

SET('filter.q', 'lamp');
// After a reload of the page, GET('filter.q') returns lamp
```

### CL(name, [callback])

Type: `method`

Loads code lists registered with `CLINIT()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | One name, or several names separated by commas. |
| `callback` | `Function` | no |  | A function that runs when the lists are loaded. |

A code list is shared data, such as a list of countries, stored in [DEF.cl](../def/). A list is loaded once. The `callback` runs when all the lists are available. A name that is not registered yet is checked again every 500 milliseconds until it appears.

Example: Load a list on demand
```js
CLINIT('countries', function(next) {
	next([{ id: 'SK', name: 'Slovakia' }]);
});

ON('ready', function() {
	CL('countries', function() {
		console.log(DEF.cl.countries.length); // 1
	});
});
```

### clearTimeout2(name)

Type: `method`

Cancels a timer created with `setTimeout2()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the timer. |

Returns: `Boolean` `true` when the timer exists.

Example: Cancel a timer
```js
setTimeout2('search', NOOP, 1000);
console.log(clearTimeout2('search')); // true
console.log(clearTimeout2('unknown')); // false
```

### CLINIT(name, source, [init])

Type: `method`

Registers the source of a code list.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the code list. |
| `source` | `Function|String` | yes |  | A function, a request or an operation. |
| `init` | `Boolean` | no | `false` | Loads the list immediately. |

When `source` is a function, it receives `next(value, [extend])`. Pass the list to `next()`. With `extend` set to `true`, `value` is an object whose keys are stored as separate code lists.

When `source` is a string, a value that starts with an HTTP method is loaded with [AJAX()](../globals/). Any other value is an operation for [TAPI()](../globals/).

Example: Load several lists at once
```js
CLINIT('all', function(next) {
	next({ colors: ['red'], sizes: ['XL'] }, true);
}, true);

ON('ready', function() {
	setTimeout(function() {
		console.log(DEF.cl.colors, DEF.cl.sizes); // ["red"] ["XL"]
	}, 100);
});
```

### CLONE(value, [raw])

Type: `method`

Creates a deep copy of a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|String` | yes |  | The value to copy, or a path. |
| `raw` | `Boolean` | no | `false` | Treats a string as a plain value. |

Returns: `Object` The copy.

A string is treated as a path to an object or an array, and the value found there is copied. With `raw` set to `true`, a string is returned as it is. Objects are copied through JSON, and dates inside them stay dates.

Example: Copy an object
```js
var a = { user: { name: 'Peter' } };
var b = CLONE(a);
b.user.name = 'Lucia';
console.log(a.user.name); // Peter
```

Example: Copy the value of a path
```js
SET('form', { name: 'Peter' });
var copy = CLONE('form');
console.log(copy); // {"name":"Peter"}
```

### CLRELOAD(name, [callback])

Type: `method`

Loads code lists again from their sources.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | One name, or several names separated by commas. |
| `callback` | `Function` | no |  | A function that runs when the lists are reloaded. |

Only lists that are already loaded are reloaded. Other names are skipped.

Example: Refresh a list
```js
var counter = 0;

CLINIT('stats', function(next) {
	next([++counter]);
});

ON('ready', function() {
	CL('stats', function() {
		CLRELOAD('stats', function() {
			console.log(DEF.cl.stats); // [2]
		});
	});
});
```

### CMD(name, [a], [b], [c], [d])

Type: `method`

Runs a command on every component that registers it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The command, optionally followed by flags. |
| `a` | `Object` | no |  | The first argument. |
| `b` | `Object` | no |  | The second argument. |
| `c` | `Object` | no |  | The third argument. |
| `d` | `Object` | no |  | The fourth argument. |

Components register commands with [command()](../component/). Flags can follow the name after a space, for example `CMD('refresh @saved')`: they are emitted first, as with [SET()](../globals/). To run a command only in a part of the page, use [$(selector).CMD()](../jquery/) or [plugin.cmd()](../plugin/).

Example: Clear every list
```html
<ui-component name="list"></ui-component>
<ui-component name="list"></ui-component>

<script>
var count = 0;

COMPONENT('list', function(self) {
	self.command('clear', value => count += value);
});

ON('ready', function() {
	CMD('clear', 1);
	console.log(count); // 2
});
</script>
```

### COMPONENT(name, [config], callback, [dependencies], [css])

Type: `method`

Registers a component declaration.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the component. |
| `config` | `String` | no |  | The default configuration in the form `key:value;key:value`. |
| `callback` | `Function` | yes |  | The declaration: `function(self, config, cls)`. |
| `dependencies` | `String|Array` | no |  | Addresses to import first, separated by commas. An array can also contain functions that receive `next`. |
| `css` | `String` | no |  | The styles of the component. |

The `callback` runs once for every instance, and receives the instance, its configuration and its CSS class. In the `css` argument, the word `CLASS` becomes `ui-` followed by the component name. See [Creating components](../../guides/creating-components/) and the [Component](../component/) object.

Example: Declare a component
```html
<ui-component name="hello"></ui-component>

<script>
COMPONENT('hello', 'name:World', function(self, config, cls) {
	self.make = function() {
		self.element.aclass(cls).html('Hello ' + config.name);
		console.log(self.element.html()); // Hello World
	};
});
</script>
```

### COMPONENTS(path)

Type: `method`

Returns the components bound to a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path, optionally with flags. |

Returns: `Array` The matching [component](../component/) instances.

The path includes everything below it, so `form` also returns a component bound to `form.name`. Flags in the path narrow the result: `@visible`, `@hidden`, `@touched`, `@modified`, `@required`, `@invalid`, `@valid`, `@disabled` and `@enabled`.

Example: Find the required fields
```html
<ui-component name="field" path="form.name" config="required:true"></ui-component>
<ui-component name="field" path="form.note"></ui-component>

<script>
COMPONENT('field', function(self) {
	self.setter = NOOP;
});

ON('ready', function() {
	console.log(COMPONENTS('form').length); // 2
	console.log(COMPONENTS('form @required').length); // 1
});
</script>
```

### CONFIG(selector, config)

Type: `method`

Changes the configuration of existing and future components.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String|Function` | yes |  | The components to configure. |
| `config` | `String|Object` | yes |  | The configuration, as an object or in the form `key:value;key:value`. |

The `selector` can be:

| Selector | Matches |
| --- | --- |
| `name` | Components with this name. |
| `#id` | The component with this identifier. |
| `.path` | Components whose path contains `path`. |
| `*` | All components. |
| `a, b` | Several selectors separated by commas. |
| `function(instance)` | Components for which the function returns `true`. |

Example: Configure by name
```html
<ui-component name="box"></ui-component>

<script>
COMPONENT('box', function(self) {});

ON('ready', function() {
	CONFIG('box', 'color:red;size:10');
	console.log(FIND('box').config.size); // 10
});
</script>
```

### COOKIES

Type: `property`

Reads and writes browser cookies.

Returns: `Object` The object with the methods.

The object has three methods:

| Method | Description |
| --- | --- |
| `COOKIES.get(name)` | Returns the value, or an empty string. |
| `COOKIES.set(name, value, [expire], [samesite])` | Writes a cookie for the path `/`. `expire` is a number of days, a `Date` or a text such as `1 day`. Without `expire`, the cookie is kept until the browser is closed. `samesite` is for example `lax`. |
| `COOKIES.rem(name)` | Removes the cookie. |

Example: Write and read a cookie
```js
COOKIES.set('theme', 'dark', '1 month', 'lax');
console.log(COOKIES.get('theme')); // dark
```

Example: Keep a cookie for a week
```js
COOKIES.set('token', 'a=1', 7);
console.log(COOKIES.get('token')); // a=1
```

### COPY(source, target)

Type: `method`

Copies the properties of one object to another.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object` | yes |  | The object to read from. |
| `target` | `Object` | yes |  | The object to write to. |

Returns: `Object` The `target` object.

Nested objects are cloned, so later changes in `source` do not affect `target`.

Example: Merge two objects
```js
var target = { a: 1 };
COPY({ b: { c: 2 } }, target);
console.log(target); // {"a":1,"b":{"c":2}}
```

### CSS(value, [id], [selector])

Type: `method`

Another name for `STYLE()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array` | yes |  | The CSS. |
| `id` | `String` | no |  | The identifier of the style element. |
| `selector` | `String` | no |  | A selector that prefixes every rule. |

See [STYLE()](../globals/). Setting `window.jc_globals = { CSS: false }` ahead of the library script leaves this global undefined.

### DAYS

Type: `property`

The English names of the days of the week, starting with Sunday.

Returns: `Array` Seven strings.

Example: Read a day
```js
console.log(DAYS[1]); // Monday
```

### DEF

Type: `property`

The default settings of the library.

Returns: `Object` The settings.

Described on its own page: [DEF](../def/).

### DECRYPT(text, [key], [type])

Type: `method`

Reads a value written by `ENCRYPT()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | The text from `ENCRYPT()`. |
| `key` | `String` | no |  | The key. |
| `type` | `String` | no |  | The prefix of the text. |

Returns: `Object` The value, or `undefined`.

The `key` and the `type` must be the ones given to [ENCRYPT()](../globals/). The method returns `undefined` when the checksum does not match them, which is the case for a changed text. A value that starts with `[`, `{` or `"` is parsed as JSON.

Example: Read an object back
```js
var text = ENCRYPT({ id: 5 }, 'secret', 'U');

console.log(text.charAt(0)); // U
console.log(DECRYPT(text, 'secret', 'U')); // {"id":5}
console.log(DECRYPT(text, 'secret')); // undefined
```

### DIFFDOM(element, selector, html, [attribute])

Type: `method`

Updates the children of an element so that they match new HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes |  | The parent element. |
| `selector` | `String` | yes |  | A selector of the compared children. |
| `html` | `String` | yes |  | The new content. |
| `attribute` | `String` | no |  | The attribute used for the comparison. |

Returns: `Object` The number of added, kept and removed elements: `{ add, upd, rem }`.

Children that have not changed stay in the DOM, so they keep their state. Children are compared by their whole HTML, or by the value of `attribute` when it is set.

Example: Update a list
```html
<ul id="list"><li>A</li><li>B</li></ul>

<script>
var list = $('#list');
var result = DIFFDOM(list, 'li', '<li>A</li><li>C</li>');
console.log(result); // {"add":1,"upd":1,"rem":1}
console.log(list.html()); // <li>A</li><li>C</li>
</script>
```

### EMIT(name, [a], [b], [c], [d])

Type: `method`

Emits an event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the event. |
| `a` | `Object` | no |  | The first argument. |
| `b` | `Object` | no |  | The second argument. |
| `c` | `Object` | no |  | The third argument. |
| `d` | `Object` | no |  | The fourth argument. |

Handlers registered with [ON()](../globals/), and handlers registered on [components](../component/) and [plugins](../plugin/), receive the arguments. Flags can follow the name, for example `refresh @loading`. The events of the library are listed in [Events](../events/).

Example: Emit a custom event
```js
ON('saved', function(id, name) {
	console.log(id, name); // 5 Peter
});

EMIT('saved', 5, 'Peter');
```

### EMPTYARRAY

Type: `property`

A frozen empty array.

Returns: `Array` An array that cannot be changed.

Example: A shared default value
```js
console.log(Object.isFrozen(EMPTYARRAY)); // true
```

### EMPTYOBJECT

Type: `property`

A frozen empty object.

Returns: `Object` An object that cannot be changed.

Example: A shared default value
```js
console.log(Object.isFrozen(EMPTYOBJECT)); // true
```

### ENCRYPT(value, [key], [type])

Type: `method`

Encodes a value as text with a checksum.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Object` | yes |  | The value. |
| `key` | `String` | no |  | The key of the checksum. |
| `type` | `String` | no |  | A prefix written at the beginning of the text. |

Returns: `String` The encoded text.

An object or an array is serialized with [STRINGIFY()](../globals/) first. The result has the `type` as a prefix, the value in hexadecimal digits, the letter `x` and a checksum made with [HASH()](../globals/) from the value, the `key` and the `type`.

The value can be read back by anyone, so do not use the method to hide data: the key only lets [DECRYPT()](../globals/) find out whether the text was changed.

Example: Encode and decode
```js
var text = ENCRYPT('hello', 'secret');

console.log(text); // 68656c6c6fxds46dr
console.log(DECRYPT(text, 'secret')); // hello
console.log(DECRYPT(text, 'other')); // undefined
```

### ENV(name, [value])

Type: `method`

Reads or writes environment variables.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Object` | yes |  | The name, or an object with names and values. |
| `value` | `Object` | no |  | The value to write. |

Returns: `Object` The value of the variable.

Variables are stored in [DEF.env](../def/). A text can refer to them as `[name]`: paths, addresses and configuration values replace this notation with the value. Pass an object to write several variables. Every write emits the `env` [event](../events/).

Example: Use a variable in a text
```js
ENV('api', '/api/v1/');
console.log(ENV('api')); // /api/v1/
console.log('[api]users/'.env()); // /api/v1/users/
```

### ENVIRONMENT(name, [version], [language], [env])

Type: `method`

Sets the storage key, version, language and environment variables of the app.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The key used in `localStorage`. |
| `version` | `String` | no |  | The version of the app. |
| `language` | `String` | no |  | The language of the app. |
| `env` | `Object` | no |  | Environment variables. |

The method assigns [DEF.localstorage](../def/), [DEF.version](../def/) and [DEF.language](../def/), and passes `env` to [ENV()](../globals/). Call it directly after the library script, so that the app reads its own storage.

Example: Configure an app
```js
ENVIRONMENT('myapp', '1.0', 'en', { title: 'My app' });

console.log(DEF.localstorage, DEF.version, DEF.language); // myapp 1.0 en
console.log(ENV('title')); // My app
```

### ERROR(response, [success], [error])

Type: `method`

Checks a response for errors and runs the matching handler.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `response` | `Object` | yes |  | The response to check. |
| `success` | `Function|String` | no |  | Runs when there is no error. |
| `error` | `Function|String` | no |  | Runs when there is an error. |

Returns: `Boolean` `true` when the response holds an error.

A response is an error when it is an `Error` object, has an `error` property, or is an array whose first item has one. An error emits the `ERROR` [event](../events/).

`success` and `error` can be functions, or names for [SEEX()](../globals/).

Call `ERROR(success, [error])` without a response to create a function that you can pass as a callback.

Example: Check a response
```js
console.log(ERROR({ id: 1 })); // false
console.log(ERROR([{ error: 'Invalid name' }])); // true
```

Example: Create a callback
```js
var callback = ERROR(function(response) {
	console.log(response.id); // 1
});

callback({ id: 1 });
```

### ERRORS(path, callback)

Type: `method`

Returns the invalid components of a path or of an element.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String|jQuery` | yes |  | A path, or an element that contains the components. |
| `callback` | `Function` | yes |  | A function that receives an array of [components](../component/). |

Example: Validate a form
```html
<ui-component name="field" path="form.name" config="required:true"></ui-component>

<script>
COMPONENT('field', function(self) {
	self.validate = function(value) {
		return !!value;
	};
});

ON('ready', function() {
	ERRORS('form', function(components) {
		console.log(components.length); // 1
	});
});
</script>
```

### EXEC(name, [a], [b], [c], [d])

Type: `method`

Calls a function by its name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The target of the call. |
| `a` | `Object` | no |  | The first argument. |
| `b` | `Object` | no |  | The second argument. |
| `c` | `Object` | no |  | The third argument. |
| `d` | `Object` | no |  | The fourth argument. |

The form of `name` decides what is called:

| Name | Calls |
| --- | --- |
| `name` | A global function. |
| `FUNC.name` | A function found at a path. |
| `plugin/method` | A method of a [plugin](../plugin/). |
| `*/method` | A method of the common plugin. |
| `-component/method` | A component method, through [SETTER()](../globals/). |
| `#event` | An event, through [EMIT()](../globals/). |

Add the flag `@important` to retry every 500 milliseconds until the function exists, for example `EXEC('app/refresh @important')`. `EXE()` is the same function under another name.

Example: Call a function by path
```js
FUNC.sum = function(a, b) {
	console.log(a + b); // 5
};

EXEC('FUNC.sum', 2, 3);
```

Example: Wait for a function
```js
EXEC('app.start @important', 'now');

setTimeout(function() {
	window.app = {};
	app.start = function(value) {
		console.log(value); // now
	};
}, 100);
```

### EXTENSION(name, [config], callback)

Type: `method`

Extends a component or a plugin.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The component name, or `@` followed by the plugin name. |
| `config` | `String|Object` | no |  | Configuration added to each instance. |
| `callback` | `Function` | yes |  | A function `(instance, config, cls)`, where `cls` is the CSS class of the instance. `this` is the instance. |

The `callback` runs for every existing instance and for every new one, right after the declaration, always with the same arguments. For a plugin, write `@` in front of its name.

Example: Add a method to a component
```html
<ui-component name="box"></ui-component>

<script>
COMPONENT('box', function(self) {});

EXTENSION('box', 'color:red', function(self, config) {
	self.describe = function() {
		return config.color;
	};
});

ON('ready', function() {
	console.log(FIND('box').describe()); // red
});
</script>
```

### FIND(selector, [all])

Type: `method`

Finds a component that is ready.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes |  | The name, the identifier or the path. |
| `all` | `Boolean` | no | `false` | Returns all the matches in an array. |

Returns: `Component|Array` The first [component](../component/), or an array when `all` is `true`.

The `selector` is a component name, `#id` for an identifier, or `.path` for a path.

Example: Find by name and by path
```html
<ui-component name="field" path="form.name"></ui-component>

<script>
COMPONENT('field', function(self) {});

ON('ready', function() {
	console.log(FIND('field').name); // field
	console.log(FIND('.form.name').path.path); // form.name
	console.log(FIND('field', true).length); // 1
});
</script>
```

### FLAGS(flags, [callback])

Type: `method`

Emits flags and then runs a function.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `flags` | `String` | yes |  | The flags, for example `@loading @save`. |
| `callback` | `Function` | no |  | A function that runs afterwards. |

Each flag emits the event `@flag name`, which you can capture with [ON()](../globals/). See [Flags and path modifiers](../../guides/flags/).

Example: Capture a flag
```js
ON('@flag loading', function() {
	console.log('flag captured'); // flag captured
});

FLAGS('@loading', function() {
	console.log('done'); // done
});
```

### FN(code)

Type: `method`

Compiles an arrow function from a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `String` | yes |  | The code of the function. |

Returns: `Function` The compiled function.

The code can have up to four arguments. Code without an arrow becomes a function with the argument `value`. Compiled functions are cached.

Example: Compile functions
```js
console.log(FN('n => n * 2')(4)); // 8
console.log(FN('(a, b) => a + b')(1, 2)); // 3
console.log(FN('value + 1')(1)); // 2
```

### FREE()

Type: `method`

Removes components, bindings and plugins whose elements have left the DOM.

The library runs this cleanup every minute. Call it when you need the instances to be removed right away.

Example: Remove a detached component
```html
<ui-component name="box" path="form.name"></ui-component>

<script>
COMPONENT('box', function(self) {});

ON('ready', function() {
	$('ui-component').remove();
	FREE();
	console.log(COMPONENTS('form').length); // 0
});
</script>
```

### FUNC

Type: `property`

An empty object for the functions of your app.

Returns: `Object` The container.

Functions stored here can be called by path with [EXEC()](../globals/).

Example: Store a function
```js
FUNC.hello = function() {
	return 'Hello';
};

console.log(FUNC.hello()); // Hello
```

### GET(path, [noflags])

Type: `method`

Reads the value of a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path, optionally with flags. |
| `noflags` | `Boolean` | no | `false` | Reads the value without applying the flags. |

Returns: `Object` The value.

When the path contains flags, they are applied to the components of the path: `GET('form @reset')` returns the value and resets their state. See [Paths](../../guides/paths/).

Example: Read values
```js
SET('user.name', 'Peter');

console.log(GET('user.name')); // Peter
console.log(GET('user')); // {"name":"Peter"}
```

### GUID([length])

Type: `method`

Generates a random identifier.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | no |  | The length of the identifier. |

Returns: `String` The identifier.

Without `length`, the result has the 36-character form of a UUID. With `length`, it is a string of lowercase letters and digits.

Example: Generate identifiers
```js
console.log(GUID().length); // 36
console.log(GUID(10).length); // 10
```

### HASH(value)

Type: `method`

Creates a numeric hash of a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Number|Boolean|Object|Date` | yes |  | The value. |

Returns: `Number` The hash.

A number is returned as it is, `true` gives `1`, a date gives its time in milliseconds, and an empty value gives `0`. Objects are serialized first.

Example: Hash a string
```js
console.log(HASH('hello')); // 99162322
```

### HIDDEN(element)

Type: `method`

Checks whether an element nested in the page is hidden.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes |  | An element placed inside another element of the body. |

Returns: `Boolean` `true` when the element is hidden.

The element counts as hidden when it has no offset parent, which is the case for `display:none`. A missing element also counts as hidden. To check the position in the viewport, use [VISIBLE()](../globals/).

Example: Check an element
```html
<main><div id="a" style="display:none"></div><div id="b"></div></main>

<script>
console.log(HIDDEN($('#a'))); // true
console.log(HIDDEN($('#b'))); // false
</script>
```

### IMPORT(url, [target], [callback], [prepare])

Type: `method`

Loads a script, a stylesheet or a piece of HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address and optional keywords. |
| `target` | `String|jQuery|Element` | no | `body` | The element that receives HTML content. |
| `callback` | `Function` | no |  | A function that runs when the content is loaded. |
| `prepare` | `Function` | no |  | A function that receives the HTML and returns the text to insert. |

Addresses ending with `.js` or `.css` are added to the page head. Any other address is downloaded and inserted into `target`. Keywords can be combined with the address:

| Keyword | Meaning |
| --- | --- |
| `<name>` | Skips the import when the global variable `name` exists. |
| `.js`, `.css`, `.html` | Sets the type of the content when the address does not show it. |
| `@singleton` | Imports the address only once. |
| `@prepend` | Inserts the content at the beginning of `target`. |

When a script or a stylesheet cannot be loaded, the library writes a warning to the console and `callback` still runs.

See [Importing content](../../guides/importing/).

Example: Insert a piece of HTML
```html
<div id="menu"></div>

<script>
IMPORT('/parts/menu.html', '#menu', function() {
	console.log($('#menu').html()); // <b>Menu</b>
});
</script>
```

Example: Skip a library that exists
```js
IMPORT('<jQuery> /js/jquery.min.js', function() {
	console.log('jQuery is available'); // jQuery is available
});
```

### INC(path, [value])

Type: `method`

Increases the number stored in a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. |
| `value` | `Number` | no | `1` | The amount to add. |

An empty path starts at `0`. A string is converted to a number. Use a negative `value` to decrease the number.

Example: Increase a counter
```js
SET('stats.visits', 10);
INC('stats.visits');
INC('stats.visits', 5);
console.log(GET('stats.visits')); // 16
```

### inDOM(element)

Type: `method`

Checks whether an element is attached to the document body.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `Element` | yes |  | A DOM element. |

Returns: `Boolean` `true` when the element is attached, otherwise nothing.

Example: Check an element
```js
console.log(inDOM(document.body)); // true
console.log(!!inDOM(document.createElement('div'))); // false
```

### isIE

Type: `property`

Tells whether the browser is Internet Explorer.

Returns: `Boolean` The result of the detection.

### isMOBILE

Type: `property`

Tells whether the user agent belongs to a mobile device.

Returns: `Boolean` The result of the detection.

### isPRIVATEMODE

Type: `property`

Tells whether `localStorage` is unavailable, as in some private windows. The value is set while the library starts, so read it from the `ready` event onward.

Returns: `Boolean` The result of the detection.

### isROBOT

Type: `property`

Tells whether the user agent belongs to a search engine or a crawler.

Returns: `Boolean` The result of the detection.

### isSTANDALONE

Type: `property`

Tells whether the page runs as an installed web app.

Returns: `Boolean` The result of the detection.

### isTOUCH

Type: `property`

Tells whether the device supports touch input.

Returns: `Boolean` The result of the detection.

### jComponent

Type: `property`

The main object of the library.

Returns: `Object` The main object.

The same object as [MAIN](../main/).

### LOCALIZE(text)

Type: `method`

Loads translations into the dictionary.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | The lines with translations. |

Each line has the form `key : translation`, and lines starting with `//` are skipped. The key is the hash of the original text, in base 36, with the prefix `T`. The translations are stored in [DEF.dictionary](../def/) and used by [TRANSLATE()](../globals/). See [Localization](../../guides/localization/).

Example: Load a translation
```js
var key = 'T' + HASH('Hello').toString(36);

LOCALIZE(key + ' : Hola');
console.log(TRANSLATE('@(Hello)')); // Hola
```

### M

Type: `property`

A short name of the main object.

Returns: `Object` The main object.

The same object as [MAIN](../main/).

### MAIN

Type: `property`

The main object of the library.

Returns: `Object` The main object.

Described on its own page: [MAIN](../main/).

### MONTHS

Type: `property`

The English names of the months, starting with January.

Returns: `Array` Twelve strings.

Example: Read a month
```js
console.log(MONTHS[0]); // January
```

### NEWUIBIND(element, [path], [config])

Type: `method`

Creates a data binding on an element from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes |  | The element. |
| `path` | `String` | no |  | The path to observe. |
| `config` | `String` | no |  | The binding commands. |

The binding works like the [ui-bind](../ui-bind/) element. Without `path` and `config`, the values are read from the attributes of the element.

Example: Bind an element to a path
```html
<div id="name"></div>

<script>
SET('user.name', 'Peter');
NEWUIBIND($('#name'), 'user.name', 'text:value');

setTimeout(function() {
	console.log($('#name').html()); // Peter
}, 200);
</script>
```

### NODEINDEXOF(element)

Type: `method`

Returns the position of an element among its siblings.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes |  | The element. |

Returns: `Number` The zero-based position.

Example: Read a position
```html
<ul><li id="a">A</li><li id="b">B</li></ul>

<script>
console.log(NODEINDEXOF($('#b'))); // 1
</script>
```

### NODEINSERT(element, reference, [before])

Type: `method`

Inserts an element next to another element.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes |  | The element to insert. |
| `reference` | `jQuery|Element` | yes |  | The reference element. |
| `before` | `Boolean` | no | `false` | Inserts the element in front of the reference. |

Example: Move an element
```html
<ul><li id="a">A</li><li id="b">B</li><li id="c">C</li></ul>

<script>
NODEINSERT($('#c'), $('#a'), true);
console.log($('ul').text()); // CAB
</script>
```

### NODEMOVE(element, [up])

Type: `method`

Moves an element one position among its siblings.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes |  | The element. |
| `up` | `Boolean` | no | `false` | Moves the element towards the start. Otherwise it moves towards the end. |

Example: Reorder a list
```html
<ul><li id="a">A</li><li id="b">B</li><li id="c">C</li></ul>

<script>
NODEMOVE($('#b'), true);
console.log($('ul').text()); // BAC
</script>
```

### NOOP()

Type: `method`

A function that does nothing.

Use it as a default callback.

Example: A default callback
```js
var callback = NOOP;
console.log(typeof(callback)); // function
```

### NOTFOCUSED()

Type: `method`

Checks whether the page is in the background.

Returns: `Boolean` `true` when the document is hidden.

Example: Check the page
```js
console.log(NOTFOCUSED()); // false
```

### NOW

Type: `property`

The current date, refreshed once a minute.

Returns: `Date` The date.

Use it when a precision of one minute is enough. It avoids creating a new `Date` object for each use.

Example: Read the date
```js
console.log(NOW instanceof Date); // true
```

### NUL(path)

Type: `method`

Sets a path to `null`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. |

`NULL()` is the same function under another name.

Example: Clear a value
```js
SET('user.name', 'Peter');
NUL('user.name');
console.log(GET('user.name')); // null
```

### OFF(name, [callback])

Type: `method`

Removes event handlers.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the event. |
| `callback` | `Function` | no |  | The handler to remove. |

Without `callback`, all the handlers of the event are removed. Several events can be joined with `+`.

Example: Remove a handler
```js
var count = 0;
var handler = function() {
	count++;
};

ON('refresh', handler);
EMIT('refresh');
OFF('refresh', handler);
EMIT('refresh');
console.log(count); // 1
```

### ON(name, callback, [init])

Type: `method`

Registers an event handler.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the event. |
| `callback` | `Function` | yes |  | The handler. It receives the arguments of the event. |
| `init` | `Boolean` | no | `false` | Also calls the handler once, without arguments. |

Several events can be joined with `+`, for example `saved + removed`. A handler for `ready` or `init` runs immediately when the library has started. The events of the library are listed in [Events](../events/).

Example: Capture two events
```js
var count = 0;

ON('saved + removed', function() {
	count++;
});

EMIT('saved');
EMIT('removed');
console.log(count); // 2
```

### PARSE(value)

Type: `method`

Parses JSON and converts date strings to `Date` objects.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Object` | yes |  | The JSON, a selector or an object. |

Returns: `Object` The parsed value, or `null`.

A value starting with `#` or `.` is a selector: the JSON is read from the content of that element. An object is returned as it is. Invalid JSON returns `null`.

Example: Parse JSON
```js
var data = PARSE('{"created":"2024-05-01T10:00:00.000Z"}');
console.log(data.created instanceof Date); // true
console.log(PARSE('invalid')); // null
```

### PIPE(name, [data], callback, [scope])

Type: `method`

Calls an operation on the address from `DEF.pipe`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the operation, optionally followed by keywords. |
| `data` | `Object` | no |  | The data of the operation. |
| `callback` | `Function|String` | yes |  | A function or a path that receives the response. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |

It works like [API()](../globals/), with the address taken from [DEF.pipe](../def/).

Example: Call an operation
```js
DEF.pipe = '/pipe/';

PIPE('orders_list', function(response) {
	console.log(response.length); // 1
});
```

### PLUGIN(name, [config], callback, [dependencies])

Type: `method`

Registers a plugin declaration.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the plugin. |
| `config` | `String` | no |  | The default configuration in the form `key:value;key:value`. |
| `callback` | `Function` | yes |  | The declaration: `function(self, config)`. |
| `dependencies` | `String|Array` | no |  | Addresses to import first. |

The `callback` runs when a [ui-plugin](../ui-plugin/) element with this path is created. The name `*` registers the common plugin. See [Plugins](../../guides/plugins/) and the [Plugin](../plugin/) object.

Example: Declare a plugin
```html
<ui-plugin path="users"></ui-plugin>

<script>
PLUGIN('users', function(self) {
	self.hello = function(name) {
		console.log('Hello ' + name); // Hello Peter
	};
});

ON('ready', function() {
	EXEC('users/hello', 'Peter');
});
</script>
```

### PLUGINS

Type: `property`

The running plugin instances, by name.

Returns: `Object` The [plugin](../plugin/) instances.

Example: Read a plugin
```html
<ui-plugin path="users"></ui-plugin>

<script>
PLUGIN('users', function(self) {});

ON('ready', function() {
	console.log(Object.keys(PLUGINS)); // ["users"]
});
</script>
```

### PREF

Type: `property`

Persistent user preferences.

Returns: `Object` The preferences.

Described on its own page: [PREF](../pref/).

### PUSH(path, value)

Type: `method`

Adds an item to the array stored in a path and notifies the path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path of an existing array. |
| `value` | `Object` | yes |  | The item. |

Write `^` in front of the path to add the item at the beginning of the array.

Example: Add items
```js
SET('tags', ['b']);
PUSH('tags', 'c');
PUSH('^tags', 'a');
console.log(GET('tags')); // ["a","b","c"]
```

### QUERIFY([url], data)

Type: `method`

Adds data to an address as a query string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | The address. |
| `data` | `Object` | yes |  | The values. |

Returns: `String` The address with the query string.

Empty values are skipped, dates are converted to ISO strings and arrays are joined with commas. The `url` can start with an HTTP method.

Example: Build addresses
```js
console.log(QUERIFY('/users/', { page: 2, q: 'a b' })); // /users/?page=2&q=a%20b
console.log(QUERIFY('GET /users/', { page: 2 })); // GET /users/?page=2
console.log(QUERIFY({ page: 2 })); // ?page=2
```

### REPO

Type: `property`

An empty object for the shared data of your app.

Returns: `Object` The container.

Example: Store a value
```js
REPO.title = 'My app';
console.log(REPO.title); // My app
```

### RESET(path)

Type: `method`

Resets the state of the components bound to a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. |

The `touched` and `modified` states return to their defaults. The value of the path does not change.

Example: Reset a form
```html
<ui-component name="field" path="form.name"></ui-component>

<script>
COMPONENT('field', function(self) {});

ON('ready', function() {
	SET('form.name @change', 'Peter');
	console.log(FIND('field').config.modified); // 1
	RESET('form');
	console.log(FIND('field').config.modified); // 0
	console.log(GET('form.name')); // Peter
});
</script>
```

### SCROLLBAR(element, [options])

Type: `method`

Adds a custom scrollbar to an element.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes |  | The element. |
| `options` | `Object` | no |  | The options. |

Returns: `Object` The scrollbar.

Options:

| Option | Type | Description |
| --- | --- | --- |
| `native` | Boolean | Keeps the scrollbar of the browser and only sets the overflow. |
| `orientation` | String | `x` or `y`. By default, both directions are active. |
| `visibleX`, `visibleY` | Boolean | Keeps the track visible when there is nothing to scroll. |
| `wrap` | Boolean | `false` uses the existing content as the scroll area. |
| `controls` | jQuery | The element that receives the scrollbar tracks. |
| `shadow` | Boolean | Adds shadows on the scrollable edges. |
| `padding` | Number | The distance of the tracks from the edge. Default `5`. |
| `minsize` | Number | The minimum size of the bar. Default `50`. |
| `thickness` | Number | The thickness used when CSS does not define it. Default `10`. |
| `margin`, `marginX`, `marginY` | Number | Adjust the size of the scroll area. |
| `offsetX`, `offsetY` | Number | Adjust the measured size of the element. |
| `floating` | Boolean | `false` reserves space for the bars. |
| `parent` | String\|jQuery | The element whose size is used. |
| `interval` | Number | The time between size checks, in milliseconds. Default `54321`. |
| `autoresize` | Boolean | `false` stops measuring the element again when the window is resized. Default `true`. |
| `onscroll`, `onidle`, `onresize` | Function | Handlers that receive the scrollbar. |

The returned object provides:

| Member | Description |
| --- | --- |
| `area` | The scrolling element. |
| `body` | The element with the content. |
| `element` | The original element. |
| `resize()` | Measures the element again. |
| `scrollTop([value])` | Reads or sets the vertical position. A string such as `'+20'` moves relative to the current position. |
| `scrollLeft([value])` | Reads or sets the horizontal position, with the same rules. |
| `scrollBottom(offset)` | Scrolls to the bottom, minus `offset`. |
| `scrollRight(offset)` | Scrolls to the right edge, minus `offset`. |
| `scroll(x, y)` | Scrolls to a position. |
| `sync(element, [direction])` | Synchronizes scrolling with another element. `direction` is `x` or `y`. |
| `destroy()` | Stops the scrollbar. |

The `scroll` and `scrollidle` [events](../events/) report scrolling.

Example: Scroll from code
```html
<div id="panel" style="width:200px;height:100px"><div style="height:600px">Content</div></div>

<script>
var scrollbar = SCROLLBAR($('#panel'));

scrollbar.area.css('overflow', 'auto');
scrollbar.resize(false, true);
scrollbar.scrollTop(30);
console.log(scrollbar.scrollTop()); // 30
scrollbar.scrollTop('+20');
console.log(scrollbar.scrollTop()); // 50
</script>
```

### SCROLLBARWIDTH()

Type: `method`

Returns the width of the scrollbar of the browser.

Returns: `Number` The width in pixels.

Example: Read the width
```js
console.log(typeof(SCROLLBARWIDTH())); // number
```

### SEEX(name, [a], [b], [c], [d])

Type: `method`

Calls a function or writes a value, depending on the name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The target. |
| `a` | `Object` | no |  | The first argument. |
| `b` | `Object` | no |  | The second argument. |
| `c` | `Object` | no |  | The third argument. |
| `d` | `Object` | no |  | The fourth argument. |

The form `plugin/method` calls a plugin method, and the name of a global function calls that function. Any other name is a path, and `a` is written to it with [SET()](../globals/).

Example: Write to a path
```js
SEEX('form.name', 'Peter');
console.log(GET('form.name')); // Peter
```

Example: Call a global function
```js
window.notify = function(text) {
	console.log(text); // Saved
};

SEEX('notify', 'Saved');
```

### SET(path, value)

Type: `method`

Writes a value to a path and notifies everything that observes it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path, optionally with flags. |
| `value` | `Object` | yes |  | The value, or a function `(current)` that returns it. |

Missing objects along the path are created. Flags are part of the path, for example `form.name @change`. The form `path[]` appends the value to an array. A function as `value` receives the current value, and its result is written. See [Paths](../../guides/paths/) and [Flags and path modifiers](../../guides/flags/).

Example: Write values
```js
SET('user.name', 'Peter');
SET('user.tags[]', 'admin');
console.log(GET('user')); // {"name":"Peter","tags":["admin"]}
```

Example: Write a value from the current one
```js
SET('cart.count', 1);
SET('cart.count', value => value + 1);
console.log(GET('cart.count')); // 2
```

### SETTER(name, [a], [b], [c], [d])

Type: `method`

Calls a method on the components that match a selector.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The selector and the method. |
| `a` | `Object` | no |  | The first argument. |
| `b` | `Object` | no |  | The second argument. |
| `c` | `Object` | no |  | The third argument. |
| `d` | `Object` | no |  | The fourth argument. |

The `name` has the form `selector/method`:

| Selector | Matches |
| --- | --- |
| `name` | Components with this name. |
| `#id` | The component with this identifier. |
| `*` | All components that have the method. |

The flag `@important` retries every 500 milliseconds until a matching component with the method exists. A component declared as lazy is created by the first call, unless the name starts with `!`.

Example: Call a component method
```html
<ui-component name="counter"></ui-component>

<script>
COMPONENT('counter', function(self) {
	self.add = function(value) {
		console.log(value); // 5
	};
});

ON('ready', function() {
	SETTER('counter/add', 5);
});
</script>
```

### setTimeout2(name, callback, timeout, [limit], [param])

Type: `method`

Runs a function after a delay, restarting the delay on each call with the same name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the timer. |
| `callback` | `Function` | yes |  | The function. |
| `timeout` | `Number` | yes |  | The delay in milliseconds. |
| `limit` | `Number` | no |  | The maximum number of calls in one waiting period. |
| `param` | `Object` | no |  | The argument of the function. |

Returns: `String` The name of the timer. A call ignored by `limit` returns nothing.

With `limit`, the delay is restarted at most `limit` times. Further calls are ignored until the function runs, so it cannot be postponed forever.

Example: Run once after the last call
```js
var count = 0;
var run = function() {
	count++;
	console.log(count); // 1
};

setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
```

### STRINGIFY(value, [compress], [fields], [encrypt])

Type: `method`

Serializes a value to JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value. |
| `compress` | `Boolean` | no | `false` | Removes empty values. |
| `fields` | `Array|Object|Function` | no |  | The keys to keep. |
| `encrypt` | `Boolean|String` | no |  | `true` encodes the JSON with [ENCRYPT()](../globals/). A string does the same and is the key. |

Returns: `String` The JSON.

With `compress` set to `true`, strings are trimmed, and empty strings, `false` and `null` are left out. The `fields` argument selects the keys: an array of allowed keys, an object where `false` excludes a key, or a function `(key, value)` that returns `true` for the keys to keep.

Example: Compress and filter
```js
var data = { name: ' Peter ', note: '', age: 30 };

console.log(STRINGIFY(data, true)); // {"name":"Peter","age":30}
console.log(STRINGIFY(data, false, ['age'])); // {"age":30}
```

Example: Encode the JSON
```js
var text = STRINGIFY({ id: 5 }, false, null, 'secret');
console.log(DECRYPT(text, 'secret')); // {"id":5}
```

### STYLE(value, [id], [selector])

Type: `method`

Adds CSS to the page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array` | yes |  | The CSS. |
| `id` | `String` | no |  | The identifier of the style element. |
| `selector` | `String` | no |  | A selector that prefixes every rule. |

An element with the same `id` is replaced. The element has the identifier `css` followed by `id`. With `selector`, every rule is prefixed with this selector.

Example: Add scoped styles
```js
STYLE('b { color: red }', 'theme', '.panel');
console.log($('#csstheme').html()); // .panel b{ color: red }
```

### TAPI(name, [data], callback, [scope])

Type: `method`

Calls a Total.js API operation on the address from `DEF.api`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the operation, optionally followed by keywords. |
| `data` | `Object` | no |  | The data of the operation. |
| `callback` | `Function|String` | yes |  | A function or a path that receives the response. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |

It works like [API()](../globals/), with the address taken from [DEF.api](../def/).

Example: Store a response in a path
```js
DEF.api = '/admin/api/';

TAPI('users_list', { page: 1 }, 'users.items');

WATCH('users.items', function(value) {
	console.log(value.length); // 2
});
```

### TEMP

Type: `property`

An object for short-lived data.

Returns: `Object` The container.

The library replaces it with an empty object every minute.

Example: Store a value
```js
TEMP.result = 5;
console.log(TEMP.result); // 5
```

### TOGGLE(path)

Type: `method`

Inverts the boolean value of a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. |

Example: Toggle a value
```js
SET('menu.open', false);
TOGGLE('menu.open');
console.log(GET('menu.open')); // true
```

### Total

Type: `property`

The main object of the library.

Returns: `Object` The main object.

The same object as [MAIN](../main/).

### TRANSLATE(text)

Type: `method`

Replaces the `@(text)` markup with translations.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | The text with the markup. |

Returns: `String` The translated text.

Text without a translation stays in its original language. Translations are loaded with [LOCALIZE()](../globals/).

Example: Translate a text
```js
LOCALIZE('T' + HASH('Yes').toString(36) + ' : Ano');
console.log(TRANSLATE('@(Yes) / @(No)')); // Ano / No
```

### UNAUTHORIZED(...permissions)

Type: `method`

Checks the permissions of the signed-in user.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `permissions` | `String` | yes |  | One or more permissions. |

Returns: `Boolean` `true` when access is denied.

The method reads the global variable `user`. A user with `sa` or `su` set has all the permissions. Otherwise, the permissions come from `user.permissions` or `user.roles`, as an array or an object. The result is `true` when the user has none of the given permissions, or when `user` does not exist.

Example: Check a permission
```js
window.user = { roles: ['editor'] };

console.log(UNAUTHORIZED('editor')); // false
console.log(UNAUTHORIZED('admin')); // true
```

### UNWATCH(path, [callback])

Type: `method`

Removes watchers from a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. Several paths can be joined with `+`. |
| `callback` | `Function` | no |  | The watcher to remove. |

Without `callback`, all the watchers of the path are removed.

Example: Stop watching
```js
var count = 0;
var watcher = function() {
	count++;
};

WATCH('form.name', watcher);
SET('form.name', 'A');
UNWATCH('form.name', watcher);
SET('form.name', 'B');
console.log(count); // 1
```

### UPD(path)

Type: `method`

Notifies a path after its value was changed directly.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path, optionally with flags. |

`UPDATE()` is the same function under another name.

Example: Notify after a direct change
```js
window.form = { name: 'A' };

WATCH('form.name', function(value) {
	console.log(value); // B
});

form.name = 'B';
UPD('form.name');
```

### VISIBLE(element, [threshold], [mode])

Type: `method`

Checks the vertical position of an element relative to the viewport.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes |  | The element. |
| `threshold` | `Number` | no | `0` | The number of pixels of the element that must be inside the viewport. |
| `mode` | `String` | no | `visible` | `visible`, `above` or `below`. |

Returns: `Boolean` The result of the check.

The `mode` selects the check: `visible` tests whether the element is in the viewport, `above` whether it is above it, and `below` whether it is below it. A hidden element returns `false`.

Example: Check an element
```html
<div id="top">Top</div>
<div style="height:5000px"></div>
<div id="far">Far</div>

<script>
console.log(VISIBLE($('#top'))); // true
console.log(VISIBLE($('#far'))); // false
console.log(VISIBLE($('#far'), 0, 'below')); // true
</script>
```

### W

Type: `property`

A short name of the `window` object.

Returns: `Object` The `window` object.

Example: Compare the objects
```js
console.log(W === window); // true
```

### WAIT(condition, callback)

Type: `method`

Runs a function when a condition is met.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `condition` | `Function|String` | yes |  | A function or a path. |
| `callback` | `Function` | yes |  | The function to run. |

The condition is checked immediately and then every 500 milliseconds. A function must return a truthy value. For a path, the wait ends when the path holds a truthy value.

Example: Wait for a value
```js
WAIT('app.config', function() {
	console.log(GET('app.config.name')); // Demo
});

setTimeout(function() {
	SET('app.config', { name: 'Demo' });
}, 100);
```

### WARN(...values)

Type: `method`

Prints a warning to the browser console.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `values` | `Object` | yes |  | The values to print. |

### WATCH(path, callback, [init])

Type: `method`

Observes changes of a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The path. |
| `callback` | `Function` | yes |  | A function that receives `(value, flags, path)`: the watched value, the flags and the changed path. |
| `init` | `Boolean` | no | `false` | Also calls the watcher once after the registration. |

A watcher runs when its own path changes, when a parent path changes, and when a path nested below it changes. Several paths can be joined with `+`.

Example: Observe a path
```js
WATCH('user.name', function(value, flags, path) {
	console.log(value, path); // Peter user.name
});

SET('user.name', 'Peter');
```

### WH

Type: `property`

The height of the window in pixels.

Returns: `Number` The height.

The value is set while the library starts, and is refreshed when the window is resized.

Example: Read the height
```js
ON('ready', function() {
	console.log(typeof(WH)); // number
});
```

### WIDTH([element])

Type: `method`

Returns the name of the device size for the width of an element.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | no | `window` | The measured element. |

Returns: `String` The name of the size.

The sizes `xs`, `sm`, `md` and `lg` are defined in [DEF.devices](../def/).

Example: Measure an element
```html
<div id="box" style="width:800px"></div>

<script>
console.log(WIDTH($('#box'))); // sm
</script>
```

### WW

Type: `property`

The width of the window in pixels.

Returns: `Number` The width.

The value is set while the library starts, and is refreshed when the window is resized.

Example: Read the width
```js
ON('ready', function() {
	console.log(typeof(WW)); // number
});
```
