tiny.js
v0.3.0
Published
A JavaScript utility library oriented to real world tasks.
Downloads
43
Readme
Tiny
A JavaScript utility library oriented to real world tasks.
Purpose
Tiny aims to stay small and simple, while powerful and really useful.
Inspired by jQuery and Underscore, but using concepts from You might not need jQuery and the power of ES6 (ES2015).
Methods are implemented individually and not as part of a whole.
Installation
There are multiple ways to use Tiny.
Inline resource (recommended)
Grab the distributable code and embed into a <script> tag just before the closing </body> tag.
Module
Use NPM or Bower and include Tiny.js as a part of the build process.
npm install tiny.jsbower install tinyFrom CDN
<script src="https://http2.mlstatic.com/ui/chico/tiny/[VERSION]/tiny.min.js"></script>Check releases to find the latest version number.
API
tiny.clone(obj)
Creates a copy of the provided object.
obj: typeObject. The object to be cloned.
Returns an Object.
tiny.extend([deep,] target, ...sources)
Copy all of the properties of the sources to the target object and returns the resulting object. The last source will override properties of the same name in previous object.
tiny.inherits(obj, superConstructor)
Inherits the prototype methods from one constructor into another.
The parent will be accessible through the obj.super_ property.
Fully compatible with standard Node.js inherits.
obj: typeObject. An object that will have the new members.superConstructor: typeFunction. The constructor Class.
tiny.isPlainObject(obj)
Validates for a valid Object.
obj: typeObject. The object to be validated.
Returns a Boolean.
tiny.EventEmitter
Node's event emitter.
The most relevant methods:
on()once()emmit()
[WIP]
See the external module and the docs for a complete reference.
tiny.DOMEvents
tiny.on(elem, event, handler, bubbles)
Attach an event handler for an event to the selected elements.
elem: typeHTMLElement|String. An HTMLElement or a CSS selector to add listener toevent: typeString. Event name.handler: typeFunction. Event handler function.bubbles: typeBoolean. Whether or not to be propagated to outer elements.
Example:
tiny.on('.btn', 'click', function(e){ /* ... */ });
tiny.on(document.querySelector('button'), 'click', function(e){ /* ... */ });tiny.off(elem, event, handler)
Remove an event handler from the element
elem: typeHTMLElement|String. An HTMLElement or a CSS selector to remove listener fromevent: typeString. Event name.handler: typeFunction. Event handler function to remove.
Example:
tiny.off('.btn', 'click', fn);
tiny.off(document.querySelector('button'), 'click', fn);tiny.once(elem, event, handler, bubbles)
Attach a handler to an event for the element that executes only once.
elem: typeHTMLElement|String. An HTMLElement or a CSS selector to add listener toevent: typeString. Event name.handler: typeFunction. Event handler function.bubbles: typeBoolean. Whether or not to be propagated to outer elements.
Example:
tiny.once('.btn', 'click', fn);
tiny.once(document.querySelector('button'), 'click', fn);trigger(elem, event, props)
Fires an event for the given element.
elem: typeHTMLElement|String. An HTMLElement or a CSS selector to add listener toevent: typeString|Event. Event name or an event object.
Example:
tiny.trigger('.btn', 'click');
tiny.trigger(document.querySelector('button'), 'click');
tiny.trigger(document.body, 'layoutchange');tiny.addClass(el, className)
Adds the specified class to an element
el: AnHTMLElementclassName:StringThe class that should be added to an element
Example:
tiny.addClass(document.body, 'example');tiny.removeClass(el, className)
Removes the specified class from an element
el: AnHTMLElementclassName:StringThe class that should be removed
Example:
tiny.removeClass(document.body, 'example');tiny.hasClass(el, className)
Determines whether is the given class is assigned to an element
el: AnHTMLElementclassName:StringThe class that should be adden to an element
Example:
tiny.hasClass(document.body, 'example'); // => falseNote: tiny.addClass, tiny.removeClass and tiny.hasClass are the methods
of a single module named classList. It can be imported entirely as
import classList from 'tiny.js/modules/classList' or as a separated methods
import {addClass, removeClass, hasClass} from 'tiny.js/modules/classList'
tiny.parent(el, [, tagname])
Get the parent of an element, optionally filtered by a tag
el: AnHTMLElementclassName:StringThe tag name of the parent to look for
tiny.next(el)
Get the next element sibling
el: AnHTMLElement
tiny.css(el, key[, value])
Get the value of a computed style for the first element in set of matched elements or set one or more CSS properties for every matched element.
el: AnHTMLElementor a valid CSS selector.key: A CSS property name. Can be an object of property-value pairs to set.value: A value to set for the property.
// Setter
tiny.css(el, 'width', 'auto');
tiny.css(el, {
width: 'auto',
height: 'auto'
});
// Getter
tiny.css(el, 'width');tiny.ajax(url, settings)
Performs an asynchronous HTTP (Ajax) request.
url: typeString. The URL to which the request is sent.settings: typeObject. Optional.cache: typeBoolean. If set tofalse, it will force requests not to be cached by the browser. Default:truedata: typeStringA data that should be passed with xhr, currently sould be formatted as query string like aa=b&c=d. As an alternativeFormDatacan be passedheaders: typeObjectA list of additional headers, for example{ 'X-Auth': 'auth-token' }context: typeObjectEvery callback will be called in context ofsettings.contextorwindowif not provideddataType: typeStringA mime type, [json,html,text]method: typeStringA valid HTTP method, [GET|POST|PUT|DELETE]credentials: typeStingUse the"include"value to send cookies in a CORS request, not supported in IE lte 9. Default is"omit"success: typeFunctionA success callback that receives response data, status and xhr object.error: typeFunctionAn error callback that receives xhr, status and error object.complete: A success callback that receives response data, status and xhr object.preload: typeBoolean. If set totrue, it will sent requests without HTTP headers to match with the preloaded resource by the browser. Default:false.
Example:
tiny.ajax(
"http://xxxx/data.json", {
success: fn,
dataType: "json",
credentials: "include"
}
);tiny.jsonp(url, settings, callback)
Performs a JSONP request
url: typeString. The URL of the requested resource.settings: typeObject. Optional.prefix: typeString. Prefix for the callback functions that handle JSONP responses. Default:"__jsonp"name: typeString|Function. A name of the callback function that handle JSONP response. Can be a function that receives the prefix and the request id (increment). Default:settings.prefix + incrementparam: typeString. A name of the query string parameter. Default:"callback"timeout: typeNumber. How long after the request until a timeout error will occur. Default:15000success: typeFunction. Success callback function.error: typeFunction. Error callback function.autoCleanup: typeBoolean. Cleans the callback function after the first call to guarantee the single execution of callback. Default:true
tiny.jcors(...args)
Tiny loader of javascript sources using CORS. Load scripts asynchronously in parallel maintaining the execution order. See jcors-loader for complete documentation.
Example:
tiny.jcors(
"http://xxxx/jquery.min.js",
function() {
$("#demo").html("jQuery Loaded");
},
"http://xxxx/jquery.cookie.js",
function() {
$.cookie('not_existing');
}
);tiny.support
Boolean values to determine which features are available in the browser.
tiny.support.animation
Verifies that CSS Animations are supported (or any of its browser-specific implementations).
Example:
if (tiny.support.animation) {
// Some code here!
}tiny.support.touch
Checks is the User Agent supports touch events.
if (tiny.support.touch) {
// Some code here!
}tiny.support.customEvent
Checks is the User Agent supports custom events.
if (tiny.support.customEvent) {
// Some code here!
}tiny.cookies
A tiny JavaScript API for handling cookies
tiny.cookies.set(key, value, options)
Create cookie
key: typeString. A cookie name.value: typeString|Object. A cookie value.options: typeObjectexpires: typeNumbre|String. Define when the cookie will be removed.path: typeString. A String indicating the path where the cookie is visible.domain: typestring. A valid domain where the cookie should be visible.secure: typeBoolean. Indicate if the cookie transmission requires a secure protocol (https).sameSite: typeBoolean|String. It’s designed to protect from so-called XSRF (cross-site request forgery) attacks.
Example:
tiny.cookies.set('ID', 1); // Create session cookie
tiny.cookies.set('ID', 2, { expires: 14 }); // Creates a cookie that expires in 14 days
tiny.cookies.set('ID', 2, { sameSite: 'None', secure: true }); // Creates a cookie with SameSite=None; Securetiny.cookies.get(key)
Read cookie
key: typeStringA cookie name to get.
Example:
var user_id = tiny.cookies.get('ID');tiny.cookies.remove(key)
Delete cookie
key: typeStringA cookie name to delete.
Example:
tiny.cookies.remove('ID');tiny.cookies.isEnabled()
Check if the cookie is supported by the browser and enabled
Example:
if (tiny.cookies.isEnabled()) {
showCookiesPolicy();
}tiny.scroll()
Get the current vertical and horizontal positions of the scroll bars. Returns an object with left and top values.
Example:
tiny.scroll(); // { left: 0, top: 1200 }tiny.offset(el)
Get the current offset of an element. Returns an object with left and top values.
el: AnHTMLElement
Example:
tiny.offset(document.querySelector('header')); // { left: 0, top: 20 }Maintenance
Oleh Burkhay (UX Front-End), and contributors.
TO-DO
Browser support
Tested on IE8+ and major browsers.
License
Licensed under the MIT license.
Copyright (c) 2015 MercadoLibre.
