baseJS is a lightweight Javascript framework for Safari, Firefox and Mobile Safari. Its original intention is to provide shortcuts for writing Javascript so that your code can use the smallest footprint possible for mobile browsing.
Get baseJS on GitHub.
Extending objects in a clean and easy-to-read manner is the core of baseJS. At its root is the base
object.
An easy method for applying a set of properties, methods, variables onto an object or multiple objects. The last argument is always the object that will be applied to the previous arguments.
Parameter | Type | Description | Optional |
---|---|---|---|
destination(s) | object | Objects that will be extended with properties | × |
properties | object | Object to extend onto the destination(s) | × |
var myObject = function(a) { return a*2; }
base.extend(myObject, { property1: 'Lorem', property2: 'Ipsum' });
base.extend(myObject.prototype, { method: function() {} });
In this example, we've created an object myObject that returns a*2. In the second line, we are assigning a few properties to the myObject variable. In the third line, we see the shortcut for creating multiple methods on myObject.prototype. This shortens the amount of code you will have to write and the verbosity of looking at multiple instance of myObject.prototype.methodName = function() {}
.
base.extend(Array.prototype, NodeList.prototype, { method: function() {} });
Alternatively, you can add an indefinite number of objects to have the last object of properties and methods applied to. In this instance, method()
will now be a function available on both Arrays and NodeLists.
base.browser.version // 531. Number browser version, according to the userAgent. base.browser.webkit // true. Boolean browser is WebKit. base.browser.opera // true. Boolean browser is Opera. base.browser.msie // true. Boolean browser is Internet Explorer. base.browser.mozilla // true. Boolean browser is Mozilla/Firefox. base.browser.msafari // true. Boolean browser is Mobile Safari (iPhone and iPod Touch).
Check if an object is an Array. JavaScript does not have any default method for doing this.
Parameter | Type | Description | Optional |
---|---|---|---|
object | object | Object to check. | × |
var myObj = {}; var myArr = []; base.isArray(myObj); // returns false base.isArray(myArr); // returns true
Convert an associative object to a query string for passing as parameters to POST or GET calls.
Parameter | Type | Description | Optional |
---|---|---|---|
object | object | Object to transcribe into a query string. | × |
var person = { first_name: 'Paul', last_name: 'Armstrong' }; base.toQueryString(person); // "first_name=Paul&last_name=Armstrong"
Iterate a function over each index inside the Array.
Parameter | Type | Description | Optional |
---|---|---|---|
iterator | function | Function to run on each object key | × |
context | object | Scope override | × |
var team = ['Paul', 'Zach', 'Jesse']; var awesome = function(person) { alert(person); }; team.each(awesome); // alerts → 'Paul' then 'Zach' then 'Jesse'
var team = ['Paul', 'Zach', 'Jesse']; var awesome = function(person) { this[person] = true; }; team.each(awesome, team); // applies team.Paul, team.Zach and team.Jesse as true
Same method as each(), but applies waits over the interval (in milliseconds) to apply to each item in the Array. This is a regular interval method and will prevent your scripts from continuing until it has completed.
Parameter | Type | Description | Optional |
---|---|---|---|
iterator | function | Function to run on each object key | × |
interval | Number | Number of milliseconds before each iteration is run (default 1000) | × |
dir | Number | -1, 1 or null. Negative gives reverse iteration. Defaults to 1. | √ |
context | object | Scope override. Defaults to none. | √ |
callback | function | Function to fire after each item has been iterated. Defaults to empty function. | √ |
This method allows you a shorthand for firing custom events from the document object. If you include a memo object when firing the event, it can be recalled by using the event input variable, such as event.memo.
Parameter | Type | Description | Optional |
---|---|---|---|
eventName | string | Name of the event | × |
memo | object | Memo parameters for the event. Defaults empty object. | √ |
function customCallback(event) { alert(event.type); // alerts → 'myEvent' } document.addEventListener('myEvent', customCallback, true); // at some other point in your application document.fire('myEvent');
A custom event has been included in baseJS that is fired on the document object called dom:loaded
. This can be useful when you need to perform DOM manipulation before the page is rendered or you want to add event listeners prior to the user being able to interact with the page.
function myPreRenderFxn() { /* … */ } document.addEventListener('dom:loaded', myPreRenderFxn, true);
A helper method for quickly creating new HTMLElements with attributes.
Parameter | Type | Description | Optional |
---|---|---|---|
type | string | The type of element to create. | × |
atts | object | Attributes to attached to the HTMLElement. Defaults to empty object. | √ |
content | string | Set the innerHTML of the element. Defaults to empty string. | √ |
new Element('a', { class: 'topLink', href: '#top' }, 'Back to Top'); // Returns the HTMLElement <a class="topLink" href="#top">Back to Top</a>
Shortcut to preventDefault and stopPropagation on events.
// Stop all links on the page from continuing to their destination href $('a').each(function(el) { el.addEventListener('click', function(event) { event.stop(); }, true); });
Override the execution scope of a function with object and optionally prepend arguments to the input.
Parameter | Type | Description | Optional |
---|---|---|---|
oScope | object | Object to override the scope of the function. | × |
arguments | * | Any additional arguments to pass. | √ |
var example = function() { this.name = 'My awesome example'; setTimeout(function() { alert(this); // alerts → Window this.sayName(); // error → window.sayName() is undefined }, 100); setTimeout(function() { alert(this); // alerts → Object example this.sayName(); }.bind(this), 100); }; example.prototype.sayName = function() { alert(this.name); // alerts → 'My awesome example' }; var a = new example();
Binding method specific for Event Listener callbacks.
Parameter | Type | Description | Optional |
---|---|---|---|
oScope | object | Object to override the scope of the function. | × |
arguments | * | Any additional arguments to pass. | √ |
var obj = { name: 'A nice demo' }; function handler(event) { alert(this.name); } document.body.addEventListener('click', handler.bindAsEventListener(obj)); // Now any click on the page alerts obj.name
Add a class to an element if it doesn't already have it.
Parameter | Type | Description | Optional |
---|---|---|---|
className | string | Name of the class to add. | × |
document.body.addClass('body'); // <body class="body">
Check if element has a given class name
Parameter | Type | Description | Optional |
---|---|---|---|
className | string | Name of the class to test against. | × |
document.body.hasClass('body'); // true or false
Safely remove a className from the HTMLElement by checking surrounding whitespace and/or the beginning and end of the class attribute. Uses the hasClass()
method.
Parameter | Type | Description | Optional |
---|---|---|---|
className | string | Name of the class to remove. | × |
document.body.removeClass('body'); // true or false
If the HTMLElement has the specified className, remove it, otherwise add it.
Parameter | Type | Description | Optional |
---|---|---|---|
className | string | Name of the class to remove. | × |
document.body.toggleClass('body'); // returns the element
Simplified get X and Y position of an element on a page. Does not compute from within scrolled elements.
This method takes no arguments.
var nav = document.getElementById('nav'); alert(nav.getXY()); // alerts Array → [xPosition, yPosition] alert(nav.getXY().x); // alerts → xPosition alert(nav.getXY().y); // alerts → yPosition
This method allows you a shorthand for firing custom events from any HTMLElement object. If you include a memo object when firing the event, it can be recalled by using the event input variable, such as event.memo.
Parameter | Type | Description | Optional |
---|---|---|---|
eventName | string | Name of the event | × |
memo | object | Memo parameters for the event. Defaults to empty object. | √ |
function customCallback(event) { alert(event.type); // alerts → 'myHtmlEvent' } var myElement = $('#nav')[0]; myElement.addEventListener('myHtmlEvent', customCallback, true); // at some other point in your application myElement.fire('myHtmlEvent');
io is a set of methods for XHR/AJAX functions.
Create a new XHR object request.
Parameter | Type | Description | Optional |
---|---|---|---|
url | string | Location to query through XHR. | × |
options | object | Override settings for making the XHR request. | √ |
Parameter | Type | Description | Optional |
---|---|---|---|
method | string | post or get form method | √ |
asynchronous | boolean | Only true supported at this time. | √ |
contentType | string | Content mime type to send. | √ |
encoding | string | Content encoding. | √ |
params | object | Object of header parameters to send with the request. | √ |
format | string | Response type assumption: 'text', 'json', 'object', 'xml' | √ |
sanitizeJSON | boolean | Whether the JSON needs to be sanitized. | √ |
onUninitialized | function | Ready state callback. | √ |
onConnected | function | Ready state callback. | √ |
onRequested | function | Ready state callback. | √ |
onProcessing | function | Ready state callback. | √ |
onComplete | function | Ready state callback. Includes response object. | √ |
onFailure | function | Ready state callback. Includes response object. (recommended) | √ |
onSuccess | function | Ready state callback. Includes response object. (recommended) | √ |
new io('/test/results.json', { format: 'json', onSuccess: function(o) { alert(o); }, onFailure: function() { alert('There was an error getting the data'); } });
Common methods performed on a String for convenience.
Check if a string is empty or only contains whitespace.
This method takes no arguments.
var myString = 'My awesome string.'; var myEmptyString = ''; myString.blank(); // returns → false myEmptyString.blank(); // returns → true
Convert a string into an HTML NodeList.
This method takes no arguments.
var newHTML = '<h1><a href="#home">Home</a><span>Go Home</span></h1>'; var header = document.getElementByID('header'); header.appendChild(newHTML.toHTML()[0]); // Append the entire node structure, starting at the first element to the #header element.
Trim any trailing whitespace from a string or optionally provide a string/regular expression selector to match against and remove from the input string.
Parameter | Type | Description | Optional |
---|---|---|---|
match | string | Regular Expression string to trim. Defaults to trailing whitespace. | √ |
var myString = 'Oops look at the whitespace '; myString.trim(); // returns → 'Oops look at the whitespace'; var daveString = 'Remove all instances of Dave. After this, Dave will not exist.'; daveString.trim(/\sDave/g); // returns → 'Remove all instances of. After this, will not exist.'
A Template is used when you have a group of objects that need to be parsed into the same formatted output. Templates are meant to be reused.
Create a template. Replaceable keys use #{key} syntax within the string.
Parameter | Type | Description | Optional |
---|---|---|---|
template | string | The markup that will be used for the template. | × |
var myTemplate = new Template('#{name} is #{age} years old.');
Parse the data object into the template, replacing #{key} with key values.
Parameter | Type | Description | Optional |
---|---|---|---|
object | object | Key/value pairs to parse into the template object. | × |
var myTemplate = new Template('#{name} is #{age} years old.'); var person1 = { name: 'Jimmy', age: '22' }; var person2 = { name: 'Janey', age: '23' }; myTemplate.parse(person1); // returns → 'Jimmy is 22 years old.' myTemplate.parse(person2); // returns → 'Janey is 23 years old.'
Use CSS selectors to get an Array or NodeList of elements in the document or context, if provided.
Parameter | Type | Description | Optional |
---|---|---|---|
selector | string | CSS query of selectors. | × |
context | HTMLElement | Context for the query. Limits scope of query. | √ |
var header = $('#header')[0]; // Selects the first object on the page with ID 'header'
var awesome = $('div.awesome', header); // Selects every instance of <div class="awesome"></div> in #header
From this point, it's possible to run the Array & NodeList methods on the variable awesome.