Basic JavaScript library from AlterSoftware, used also by other JavaScript modules.
Current version: 1.51 (2020-11-25)
Basic usage, loading from Altersoftware CDN:
<script type="text/javascript" src="https://cdn.altersoftware.org/js-as-core/as-core.js" charset="UTF-8"></script>
Other Altersoftware modules can be loaded together, using modules
comma separated attribute in the script
tag.
E.g. if we want to load js-as-labels
and js-as-form
we can use:
<script type="text/javascript" modules="labels, form" src="https://cdn.altersoftware.org/js-as-core/as-core.js" charset="UTF-8"></script>
Modules are loaded in declaration order, beware of prerequisites — in this case js-as-labels
must be loaded before js-as-form
.
All downloads are refreshed daily from the latest stable branch of Altersoftware GIT repository.
Creates a clone of a data array, including neted arrays and/or objects.
Note: Array shouldn't contain any code reference, leafs can only be string or numbers.
Converts bytes integer into smart IT representations
console.log(Number(12334445566).smartSize());
// returns --> "11.5 GB"
console.log(Number(4200).smartSize());
// returns --> "4.1 kB"
Returns the string removing HTML tags and quotes, if any.
Use:
console.log('Hello, <b>today</b> 3 > 2 is "true"!'.dehtml());
// returns --> "Hello, today 3 > 2 is true !"
Returns the string escaping HTML tags, if any.
Use:
console.log('Hello, <b>today</b> 3 > 2 is "true"!'.escape());
// returns --> "Hello, <b>today</b> 3 > 2 is \"true\"!"
Returns the string parsing it as a SQL timestamp, in a smart format.
Use:
console.log('2021-01-15 03:05:10'.escapeDate());
// returns --> "15.1.21, 3:05"
Returns the string shortened.
A single object parameter is allowed, for options in the form of key/value.
Options and all keys are optional, and have a default value.
console.log('Hello, <b>today</b> 3 > 2 is "true"!'.shorten());
// returns --> "Hello, <b>today</b> 3 > 2 is \"true\"!"
console.log('Hello, <b>today</b> 3 > 2 is "true"!'.shorten({html:true, max:16});
// returns --> "Hello, today 3…"
Returns the string trimming leading and trailing white spaces, if any.
Adds a class to one or more DOM nodes.
Requires two parameters:
Note: in case jQuery is loaded this method relies on $(obj).addClass(className)
Returns the arguments
of a function or a NodeList
as a regular array.
function delayer() {
// Call a funcion in timeout
// first argument: function name
// then every other argument.
let ags = AS.args2array(arguments);
let funcName = ags.shift();
return setTimeout( function(){ window[funcName].apply(window,ags); }, 100);
}
// or the equivalent of AS.getNodes('div'):
let arrayOfNodes = AS.args2array( document.querySelectorAll('div') );
Returns default value for a tested object.
AS.def.arr( var )
— returns var
if Array, [var]
if scalar, []
otherwhise.AS.def.bool( var )
— return var
if Boolean, false
otherwhise.AS.def.num( var )
— returns var
if Number, parseFloat(var)
if defined, 0
otherwhise.AS.def.obj( var )
— returns var
if Object, {}
otherwhise.AS.def.str( var )
— returns var
if String, String(var)
if defined, ''
otherwhise.Accepts single parameter, a DOM node.
Returns an array of class names.
Accepts a single parameter, returns an array of DOM nodes.
param (mandatory) can be a DOM Node, an array of DOM Nodes, a NodeList or a CSS selector string.
Return a random generated ID, optionally with a “base”.
console.log(AS.generateId());
// returns something like: "asTempId_ygDMuUTN1UTNzEDNyYDO3MjMMC41NDQ0NjE0ODExNTI5MDg4"
console.log(AS.generateId('tempDiv'));
// returns something like: "tempDiv_gTNy4CO1UjNwcDNzITM5AjNMC4yODAyMzY0MjI4MzIwOTMxNg"
Returns true
if obj has class className, false
otherwhise.
Requires two parameters:
If multiple nodes are passed (as a NodeList, through selector or in an array) returns true
if at least one of the nodes has class className.
Returns the Node id attribute of param, in case it’s missing generates a new ID and returns it.
param (mandatory) can be a DOM Node, an array of DOM Nodes, a NodeList or a CSS selector string.
If multiple nodes are passed (as a NodeList, through selector or in an array) only the first node is considered.
In case param (or its first element) isn’t a Node, returns false
.
Loads the css file(s) by appending the node(s) to the HEAD
element.
Checks for duplicates, wraps load errors (reported in console).
Returns the number of files loaded.
css parameter can be:
link
HTMLElement with all its attributes.Loads the js file(s) by appending the node(s) to the HEAD
element.
Checks for duplicates, wraps load errors (reported in console).
Returns the number of files loaded.
js parameter can be:
script
HTMLElement with all its attributes.Set path strings, or return specific path strings.
Default values are:
{
webroot : '/',
currentstyle : '/style:default',
allstyles : '/style:'
}
If the argument is a string it returns the corresponding path
.
If the argument is a key/value Oject it's used to set path
values, and returns the path
Object.
path
values can be defined in the page also using META
tags, e.g.:
<meta name="AS.path.webroot" content="/myapp" />
<meta name="AS.path.currentstyle" content="/myapp/styles/mystyle" />
<meta name="AS.path" allstyles="/myapp/styles/" labels="/myapp/locales/mypage-" />
Removes a class from one or more DOM nodes.
Requires two parameters:
Note: in case jQuery is loaded this method relies on $(obj).removeClass(className)
Toggles a class from one or more DOM nodes.
Requires two parameters:
Note: in case jQuery is loaded this method relies on $(obj).toggleClass(className)
Tests window/environment, returns a Boolean.
AS.test.iOS()
— is current browser a Safari Mobile?AS.test.isTouch()
— is current browser on a touch device?Tests if a variable is a specific format, returns a Boolean.
AS.test.arr( var )
— is var an Array?AS.test.bool( var )
— is var a Boolean?AS.test.date( var )
— is var a Date?AS.test.def( var )
— is var defined? (not undefined)AS.test.func( var )
— is var a function?AS.test.j( var )
— is var a jQuery Object?AS.test.num( var )
— is var a Number?AS.test.node( var )
— is var an HTML element?AS.test.obj( var )
— is var an Object?AS.test.str( var )
— is var a String?AS.test.udef( var )
— is var undefined?Please note:
AS.test.obj( anArray )
returns true
, because an array is an object.AS.test.obj( DomNode )
returns true
, because an HTML element is an object.Returns version number.
Except for .style.display set to none
, ensure that the node(s) is/are visible before invoking the transition, meaning: visible if style.display is empty, otherwise the transition won’t have any visible effect on a non-visible element.
Check for:
The node(s) must be visible right before invoking the transition (both in and out transitions).
In case change node’s .style properties value before invoking the transition.
At the end of the transition Node’s style.display is set to:
none
if transition is Out/Up (object disappears)Performs the “fade in” animation of an HTML Element (or elements).
The first parameter is a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.
Following parameters are optional, and regardless of the order they can be:
duration
: the amount in mSec of the effect, defaults to 300
.effect
: the transition effect used, defaults to ease
.callback
: the function invoked at the end of the effect, passing the node as parameter. Defaults to false
(no callback).Reverse: AS.fadeOut()
Performs the “fade out” animation of an HTML Element (or elements).
Uses the same parameters as AS.fadeIn()
Performs the “slide down” animation of an HTML Element (or elements).
The first parameter is a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.
Following parameters are optional, and regardless of the order they can be:
duration
: the amount in mSec of the effect, defaults to 300
.effect
: the transition effect used, defaults to ease
.callback
: the function invoked at the end of the effect, passing the node as parameter. Defaults to false
(no callback).Reverse: AS.slideUp()
Performs the “slide in” animation of an HTML Element (or elements).
The first parameter is a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.
Following parameters are optional, and regardless of the order they can be:
duration
: the amount in mSec of the effect, defaults to 300
.top
or bottom
: the direction the slide comes from, defaults to top
.effect
: the transition effect used, defaults to ease
.callback
: the function invoked at the end of the effect, passing the node as parameter. Defaults to false
(no callback).Reverse: AS.slideOut()
Performs the “slide out” animation of an HTML Element (or elements).
Uses the same parameters as AS.slideIn()
Performs the “slide up” animation of an HTML Element (or elements).
Uses the same parameters as AS.slideDown()
as-core
offers a few facilities for cookies management.
Returns a string with the URI-decoded value of the cookie named cookieName.
Returns an object with cookies.
Object keys are the names of the cookies, values are the URI-decoded related string values.
Sets the value of cookie name to value (string value).
value defaults to empty string, and is automatically URI-encoded.
options is an optional object, that can have the following optional keys:
path
(string): the path of the cookie (defaults to current directory)domain
(string): the domain of the cookie (defaults to no domain, e.g.: current hostname)firstLevel
(boolean): if true the domain
will be first level (www.foo.org
=> foo.org
), and this will include all subdomains (*.foo.org
) as well.maxAge
(integer): the maximum age of the cookie, in seconds.expires
(Date or string): expiration date of the cookie. If a string it’s expected to be a date in UTC format, see: Date.toUTCString()
for more information.Returns the string used to set cookie.
Note: if domain
is specified the coookie by default is set on both the domain and its subdomains, e.g.: it’s set with a leading .
Deletes the cookie name, if any.
See AS.setCookie()
for optional options.
Warning: to succesfully delete a cookie path
and domain
values must match.
Note: cookies deletion is operated twice, using domain
both with and without a leading .
This workaround permits to delete also cookies set by Apache RewriteRule
s using [CO=…]
flag, as well as cookies set on domain and subdomains.
If no domain is provided it’s operated without domain and with domain '.' + location.hostname
AS object offers a few methods wrapping standard event commands:
event.detail
propertyAdds an event listener to DOMnode, if possible.
Works exactly like DOMnode.addEventListener( eventType, function ), actually wraps it, in addition:
AS.addEventIfNot()
possible, becauseAS.listEvents()
Notes:
default
.Adds an event listener to DOMnode, if possible, only if there’s not an event of type eventType already defined for DOMnode with any key.
Notes:
AS.addEvent()
can be considered.default
.Adds an event listener to DOMnode, if possible, only if there’s not an event of type eventType already defined for DOMnode with key.
Notes:
AS.addEvent()
can be considered.default
.If eventType and key are provided returns an array of function event handlers defined for that DOMnode on eventType for key.
If eventType is provided returns an object: keys are key properties, each value is the related above mentioned array.
In case eventType and key aren’t provided returns an object: keys are eventTypes, each value is the related above mentioned object.
Notes:
AS.addEvent()
can be considered.Triggers an event, standard or custom, on DOMnode.
Custom events must contain the ':' character to be recognized, it’s good practice to use it as a kind of "namespace" (e.g.: as:change
).
In case a CustomEvent is triggered it can optionally carry additional data, that will be received by event handlers in event.detail
property.
MutationObserver
MutationObserver introduces a new approach to Mutation Events.
Using AS.observe()
and AS.observeAttr()
methods makes it easier to handle with mutations and related notifications.
Both AS.observe()
and AS.observeAttr()
can be triggered on a Node
, on an array of Node
s, on a NodeList
or using a CSS selector string.
Both AS.observe()
and AS.observeAttr()
return an array of objects with properties node
and observer
, to stop it don’t forget to use observer.disconnect()
.
The return value is always an array, also on a single node, because they accept multiple nodes.
Creates and starts MutationObserver
object(s).
params is a mandatory object parameters object with the following keys:
node
(mandatory), the DOM node(s) as Node
, array of Node
s, NodeList
or CSS selector string.config
(mandatory), a JavaScript object with at least the keys attributes
or childList
set to true
.subtree
key set to true
, to observe also the subtree of childList
.callback
(mandatory), a function object (or the name of a global function) that will be invoked on mutations.Returns an array of objects with properties node
and observer
, to stop it don’t forget to use observer.disconnect()
.
An efficient wrap to observe DOM node(s) attributes.
params is a mandatory object parameters object with the following keys:
node
(mandatory), the DOM node(s) as Node
, array of Node
s, NodeList
or CSS selector string.attribute
(optional), a string or an array of strings with the name of the observed attribute(s).callback
(mandatory), a function object (or the name of a global function) that will be invoked on attributes mutations.context
(optional): the context (this
) of the callback when it will be invoked. Defaults to window
.Returns an array of objects with properties node
and observer
, to stop it don’t forget to use observer.disconnect()
.
When mutations happen they’re grouped together, filtered by attribute
(s) (if any).
Only one cumulative notification per node is sent back to params.callback
, with 3 parameters:
class
becomes className
.attribute
, the attribute name (in this case className
remains class
)mutation
, the MutationRecord objectA convenient shortcut to have a DOM node reflecting another DOM node attribute (e.g.: className, value, disabled etc.)
Parameters:
sourceNode
(Mandatory), the node(s) observing. Can be a Node
, an array of Node
s, a NodeList
or a CSS selector string.observedNode
(Mandatory), the node(s) being observed. Can be a Node
, an array of Node
s, a NodeList
or a CSS selector string.attributeName
(Mandatory), the attribute(s) being reflected. Can be a string or an array of strings with the name of the attribute(s).setProperty
(Boolean, optiona), if set to true
the attribute will also be set as a property of sourceNode
. Ensure you use it only when it makes sense, e.g.: on value
, disabled
, checked
or similar attributes.Extends jQuery with the $.postJSON()
method.
This method invokes a remote method and passes in the body of the request the serialized JSON of parameters, rather than a regular form.
contentType
of the request is set to application/json
,
Parameters are:
Returns the ID of an object, in case it hasn't an ID attribute it's generated on the fly and returned.
Accepts one or two parameters:
AS.generateId()
.Returns a jQuery object (if exists) or false
.
Accepts one or two parameters:
#
.POST
s to a remote WebService and returns the response to a callback.
Parameters accepted are up to 4, in whatever order:
type:post
) — Only accepts literal values type:post
, type:get
or type:json
. Use this parameter with type:json
to force the use of $.postJSON()
.In case data
is undefined then a rnd
parameter is added (to avoid cache issues) populated with a random number.
Note: for both
POST
andGET
data will be a plain key/value representation, like in a form.
When data parameter is a JavaScript object, then in case one of its keys starts with "j" and its value is an object (rather than to a scalar value, Number or String), then the related value will become the JSON String of the object.
This can be very useful if you want to pass to the remote WebService a parameter containing a JSON object.
Accepts an array of array.
Each array item is an array with up to 4 entries (AS.ws()
parameters) that will be used to invoke sequentially AS.ws()
.
When a request is fullfilled, including the callback if any, the following WebService is processed.
This is a compact basic toolbox, doesn’t change very often.
AS.load()
relying onto AS.loadCSS()
and AS.loadJS()
AS.loadCSS()
and AS.loadJS()
AS.reflectAttr()
MutationObserver
: AS.observe()
and AS.observeAttr()
.