0.3.0 • Published 5 years ago

innate.js v0.3.0

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

innate.js

A micro library (3Kb) eliminating the need for jQuery for most common tasks.

innate.js does not have any dependencies and is licensed under the terms of the MIT License.

Why?

In many scenarios we need only a small part of jQuery's functionality, but nontheless we load the whole library even though we need only 10% of it. innate.js aims to eliminate the need of jQuery and endorses the use of vanilla JS.

innate.js provides:

  • DOM querying
  • easy class manipulation
  • working with collections of elements to perform a single task
  • ajax functions
  • attribute and data manipulation
  • event binding
  • CSS accessor and manipulator
  • form serializer
  • ...

Admittedly, a lot of code is borrowed form plainjs.com, but innate.js provides the ease of use of jQuery when working with a collection of elements or even starting from CSS selectors.

Usage

The $ global carries all the available methods. To query the DOM for example, the find() method can be used:

// get elements by CSS selector
var elements = $.find( '.my-selector' )

Note that most methods accepting a selector as the first argument will return an array with the result of the DOM query.

In innate.js, methods can't be chained like in jQuery. But instead of a selector, innate.js also accepts an existing array of elements:

var el = $.addClass( 'section.my-class', 'active' )
el = $.css( el, {
  color: 'pink'
, 'font-size': '2em'
})

Or even a NodeList or HTMLCollection instance:

var elements = document.getElementsByClassName( 'my-class' )
var el = $.attr( elements, 'disabled', 'disabled' )

So where you are used to the following method chain in jQuery:

$( '[data-value]' )
  .addClass( 'highlighted' )
  .css({ color: 'pink' })
  .on( 'click', function( event ) {
    alert( event )
  })

In innate.js the same will look like:

var el = $.addClass( '[data-value]', 'highlighted' )
$.css( el, { color: 'pink' })
$.on( el, 'click', function( event ) {
  alert( event )
})

This syntax allows you to easily mix innate.js with vanilla JS and jump between the two whenever needed. Because with jQuery you will always have to unwrap the object first to access its native properties.

DOM querying

$.find()

returns: array

Get an element list for the given selector.

var el = $.find( 'div' )

Optionally, it allows a context to be passed as the second parameter (defaults to document):

$.find( 'a.social', $.first( '#main_content' ) )

$.first()

returns: Element

Get a single element for the given selector.

var element = $.first( 'header' )

Optionally, it allows a context to be passed as the second parameter (defaults to document):

$.first( 'nav', document.querySelector( 'header' ) )

DOM manipulation

$.appendTo()

returns: array

Appends a given element or list of elements to the given parent in the second parameter, which can be a selector or an element.

$.appendTo( document.createElement( 'div' ), 'body' )

$.prependTo()

returns: array

Appends a given element or list of elements to the given parent in the second parameter, which can be a selector or an element.

$.prependTo( document.createElement( 'div' ), 'body' )

$.insertAt()

returns: array

Inserts one or more elements to the given parent at a given position.

$.insertAt( document.createElement( 'div' ), 'body', 3 )

The position parameter can also be another child element of the parent.

var header = $.first( 'header' )
$.insertAt( document.createElement( 'div' ), header, header.children[5] )

Note that if the element passed as the position parameter is not a child of the parent, the elements will be inserted starting at position 0.

$.remove()

returns: array

Remove one or more elements from the DOM.

$.remove( '.removable' )

$.element()

returns: Element

Convert a HTML string to a DOM node.

$.element( '<div id="innate_id" class="innate-class">' )

Events

$.on()

returns: array

Bind an event to the given element list.

$.on( 'a', 'click', function() {
  console.log( 'innate.js' )
})

The fourth parameter will take an object with options:

$.on( 'a', 'click', handler, options )

$.off()

returns: array

Unbind an event to the given element list. This works exactly the same as $.on():

$.off( 'a', 'mousemove', handler )

$.live()

returns: array

Attach an event handler for all elements which match the current selector, now and in the future:

$.live( 'body', 'click', 'a', handler )

The fifth parameter will take an object with options:

$.live( document, 'click', 'a', handler, options )

$.trigger()

returns: array

Trigger an event type on the given element list:

$.trigger( 'a.cancel-button', 'click' )

CSS

$.show()

returns: array

Shows all elements.

$.show( 'div.tucked-away' )

$.hide()

returns: array

Hides all elements.

$.hide( 'div.in-the-way' )

$.toggle()

returns: array

Toggles visibility of all elements.

$.toggle( 'div.toggle-away' )

Optionally, a second parameter can be passed to toggle based on a boolean value:

$.toggle( 'div.toggle-away', true )

$.css()

returns: array as setter returns: value as getter

Sets a single CSS property:

$.css( 'div > p', 'color', 'pink' )

Sets multiple CSS properties:

$.css( 'div > p', {
  color: 'pink'
, display: 'inline'
})

Gets a CSS property of the first element found:

var color = $.css( 'div > p', 'color' )

Gets an object with all CSS properties of the first element found:

var properties = $.css( 'div > p' )

Attributes

$.attr()

returns: array as setter returns: value as getter

Sets a single attribute on all elements:

$.attr( 'input', 'style', 'color:pink' )

Sets multiple attributes:

$.attr( 'input', {
  style: 'color:pink'
, disabled: 'disabled'
})

Gets an attribute of the first element found:

var disabled = $.attr( 'input', 'disabled' )

Gets an object with all attributes of the first element found:

var attributes = $.attr( 'form' )

$.removeAttr()

returns: array

Removes an attribute:

$.removeAttr( 'input[type=submit]', 'disabled' )

$.data()

returns: array as setter returns: value as getter

Sets a single data attribute on all elements:

$.data( '#mydiv', 'color', 'pink' )

Sets multiple data attributes:

$.data( '#mydiv', {
  color: 'pink'
, size: 'XXS'
})

Gets a data attribute of the first element found:

var color = $.data( '#mydiv', 'color' )

Gets an object with all data attributes of the first element found:

var data = $.data( '#mydiv' )

$.removeData()

returns: array

Removes an data attribute:

$.removeData( '#mydiv', 'color' )

Classes

$.hasClass()

returns: boolean

Tests the existance of a class on the first element found:

$.hasClass( '#mydiv', 'fabulous' )

$.addClass()

returns: array

Adds a class to all elements:

$.addClass( '.menu-items', 'fabulous' )

$.removeClass()

returns: array

Removes a class from all elements:

$.removeClass( '.menu-items', 'fabulous' )

$.toggleClass()

returns: array

Toggles a class on all elements:

$.toggleClass( '.menu-items', 'fabulous' )

Optionally, a third parameter can be passed to toggle the class based on a boolean value:

$.toggleClass( '.menu-items', 'fabulous', true )

Ajax

$.get()

returns: XMLHttpRequest

Perform a simple AJAX GET request:

$.get( '/api/item/1.json', function( xhr ) {
  console.log( xhr )
})

$.post()

returns: XMLHttpRequest

Perform a simple AJAX POST request:

$.post( '/api/item/1.json', function( xhr ) {
  console.log( xhr )
})

$.ajax()

returns: XMLHttpRequest

Perform an extended AJAX POST request:

$.ajax( '/api/item/1.json', {
  // method (or type works too)
  method: 'PUT'

  // data (object will be serialized)
, data: {}

  // callbacks
, success: function() {}
, complete: function() {}
, error: function() {}
, abort: function() {}

  // headers
, headers: {}
})

Utilities

$.each()

returns: array

Iterates a the matching elements:

$.each( 'form input[]', function( element, index ) {
  element.id = 'input_' + index
})

But it also works for arrays:

$.each( [ 1, 2, 3 ], function( item, index ) {
  console.log( item )
})

$.toArray()

returns: array

Converts an a NodeList or HTMLCollection to an array:

var array = $.toArray( document.getElementsByTagName( 'li' ) )

But it can also be used to clone a given array:

var clone = $.toArray( [ 1, 2, 3 ] )

$.extend()

returns: object

Extends the first given object with the second one and returns the first:

var object = { a: 1, b: 2 }
$.extend( object, { c: 3 })

$.offset()

returns: object

Get the cumulative offset of an element:

var offset = $.offset( '#mydiv' )
var left = offset.left
var top = offset.top

$.serialize()

returns: string

Serializes and escapes the key/value pairs in a form:

var data_string = $.serialize( form )

This also works with a selector:

var data_string = $.serialize( '.main-form' )

Note: an empty string will be returned if the first matched element is not a <form>.

Finally, a closure can be provided as the second argument to filter out element values:

var data_string = $.serialize( '.main-form', function( input ) {
  return input.nodeName === 'INPUT'
})

No conflict mode

By default, innate.js uses the $ namespace. If you want to use it in conjuction with another library using $, just enable no-conflict mode:

innate.noConflict()

This will remove innate from the $ variable and restore the original owner.

Optionally, you can define a custom namespace:

innate.noConflict( 'I' )

That way, innate will be available as I:

var elements = I.find( '.some-class' )