Dough.js

/*

 * Dough.js is a common yet a bit different JS library.

 *

 * It supports both collection-wide and granular actions,

 * easy CSS transforms, CSS animation and transition

 * callbacks, explicit CSS toggling and is generally

 * very cute.

 *

 * It's also super light since it works only on modern

 * desktop and mobile browsers :D

 *

 *

 * Check the docs below and have a good time...

 */

Dough supports modern browsers, and should do well on Google Chrome, Firefox, Safari, Internet Explorer 9+, iOS and Android 2+.

What's Different?

Collection Methods

Dough's instance methods are performed collection-wide, that is - they are executed on every element in the Dough object (Except for some obvious exceptions like find(), next() and others).

The library could have had lots of polyfills but ultimately it was designed to have methods for actions that have no native alternative, especially for bulk actions.

Hence, it behaves a bit differently than other libraries. For example, executing $("p").html() will set the HTML contents of every element in the collection to an empty string and won't return the HTML contents of the first element in the collection. The same goes for attr().

This happens because there's no need for a polyfill method to get the HTML contents of the first element (or any element) in the collection, one could just use $("p")[0].innerHTML or $("a")[2].getAttribute("href") which are already supported on Dough's target browsers and will always be much more performant.

Granular Execution

Every collection-wide Dough method supports executing its action on a specific element in the collection. This means you don't need re-create a Dough object just to play with a specific element, like this:

var buttons = $(".button").removeClass("shiny-base");

// Money money money...
for (var i = 0; i < buttons.length; i++) {
    $(buttons[i]).addClass("shiny-" + randomNumber());
}

You could just do this:

for (var i = 0; i < buttons.length; i++) {
    buttons.addClass("shiny-" + randomNumber(), i);
}

buttons.off("click", 2); // And this, if it makes sense

Just use the element's index as the last parameter.

Console Printing

The Dough object isn't a true Array, so printing it using console.log() won't yeild the same result as jQuery...

Core (Query)

Dough( selector ) or $( selector )

Matches elements in the DOM with the given selector or wraps a given DOM element object(s) in a Dough object.

Parameters

selector 
(string) CSS selector, (HTMLElement) DOM element or any other array/collection (NodeList) of DOM elements

Returns

A Dough object containing the matched element(s).

Like This

// CSS selector
$("a");

// DOM element
element.addEventListener("click", function(this) {
    var me = $(this);
});

// Multiple DOM elements
$(document.querySelectorAll("a"));

// Multiple DOM elements II (Array)
var bulbasuar = document.querySelector(".bulbasaur"),
    charmander = document.querySelector(".charmander"),
    squirtle = document.querySelector(".squirtle");

$([ bulbasuar, charmander, squirtle ]);

find( selector )

Matches elements in the first element in the collection with the given selector.

Parameters

selector 
(string) CSS selector

Returns

A Dough object containing the matched element(s).

Like This

$(".my-list").find("li").addClass("ghosts");

next()

Gets the successor element of the first element in the collection.

Parameters

None 

Returns

A Dough object containing the successor element.

Like This

$(".my-li").next().addClass("bitch");

previous()

Gets the predecessor element of the first element in the collection.

Parameters

None 

Returns

A Dough object containing the predecessor element.

Like This

$(".my-li").next().addClass("queen");

each( fn )

Invokes a given function on every element in the collection. The function is provided with the element as a DOM element object.

Parameters

fn 
(function) Function to invoke on every element

Returns

The same Dough object for further method chaining.

Like This

var rainbow = "";

$(".button-shiny").each(function(element) {
  // Element is an HTMLElement object
 rainbow += element.getAttribute("data-color");
});

console.log("pretty colors: " + rainbow + "!");

Manipulation

html( value[, index] )

Sets the HTML contents of every element in the collection (or of a specific element).

Parameters

value 
(string) HTML to set as the content
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining. Notice: When no value is set - the method won't return the HTML contents (use $("a")[0].innerHTML instead).

Like This

// Happy puppies
$("a").html("Beyoncé Beyoncé, Shakira Shakira");
$("a").html("Beyoncé", 0); // Happy puppy (Granular)

// Dough.js performs collection-wide methods,
// so this just sets an empty string as the
// HTML content of every element...
$("div").html();

// This is how you'd retrieve HTML content
$("p")[3].innerHTML; // Since the dawn of the kittenet

before( content[, index ] )

Appends content to the page before every element in the collection (or before a specific element).

Parameters

content 
(string) HTML markup to add as the content, (HTMLElement) DOM element or any other array / collection (NodeList) of DOM elements
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

// HTML string;
$("li").before("<li>I'm lazy!</li>");
$("li").before("<li>I'm lazy!</li>", 0); // Granular

// DOM element object
var e = document.createElement("li");
li.innerHTML = "I'm nice";
$("li").before(e);

after( content[, index ] )

Appends content to the page after every element in the collection (or to a specific element).

Parameters

content 
(string) HTML markup to add as the content, (HTMLElement) DOM element or any other array / collection (NodeList) of DOM elements
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

// HTML string;
$("li").after("<li>I'm lazy!</li>");
$("li").after("<li>I'm lazy!</li>", 0); // Granular

// DOM element object
var e = document.createElement("li");
li.innerHTML = "I'm nice";
$("li").after(e);

attr( name[, value, index] )

Sets or removes an attribute for every element in the collection, based on the given parameters (or for a specific element).

Parameters

name 
(string) Name of the attribute to modify
value 
(string) Value to set to the attribute
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining. Notice: When no value is set - the method will remove that attribute and won't return the value of that attribute (use $("a")[0].getAttribute("href") instead).

Like This

// Happy kitties
$("a").attr("href", "http://pleasehelpmebeyonce.com");
$("a").attr("href", "http://nowhere.com", 0); // Happy kitty (Granular)

// Dough.js performs collection-wide methods,
// so this just removes the attribute since it
// has no meaning being empty... (sorry if it has)
$("a").attr("href");

// This is how you'd retrieve an attribute's value
$("a")[0].getAttribute("href"); // Since forever

CSS

addClass( classes[, index ] )

Adds one or more CSS selector classes to every element in the collection (or to a specific element).

Parameters

classes 
(string) CSS selector class(es)
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$("a").addClass("sugar-free carbon-free");

// Granular 
$("a").addClass("sugar-free", 0);

removeClass( classes[, index ] )

Removes one or more CSS selector classes from every element in the collection (or from a specific element).

Parameters

classes 
(string) CSS selector class(es)
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$("a").removeClass("sugar carbon");

// Granular 
$("a").removeClass("sugar", 0);

toggleClass( classes[, isAdd, index ] )

Adds or removes one or more CSS selector classes from every element in the collection, according to its presence (or from a specific element). Supply isAdd to perform a specific action - addition or removal.

Parameters

classes 
(string) CSS selector class(es)
isAdd 
(boolean) Explicit flag for performing an addition or removal action. Must be either true or false
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$("a").toggleClass("diet zero");
$("a").toggleClass("diet", 0); // Granular

// Explicit addition
var isActive = true;

if (isActive) {
  // Do important stuff
} else {
  // Other stuff
}
$("a").toggleClass("active", isActive); // Adds 'active'

$("a").toggleClass("active", isActive); // Still adds
isActive = false;
$("a").toggleClass("active", isActive); // Removes 'active'

// // Granular execution with explicit action
$("a").toggleClass("zero", true, 0); // Removes from 1st element

hasClass( classes[, index ] )

Determines whether every element in the collection has one or more CSS selector classes (or whether a specific element has).

Parameters

classes 
(string) CSS selector class(es)
index 
(integer) Collection element's index to perform this action on

Returns

Boolean value for the presence of the CSS selector class(es).

Like This

// Every <a> has 'light' and 'lite'
$("a").hasClass("light lite"); // = true

// Only the  <a> has 'light' but only some have 'lite'
$("a").hasClass("light lite"); // = false

// Granular
$("a").hasClass("light lite", 0);

css( styles[, value, index] )

Sets or removes inline styling for every element in the collection, based on the given parameters (or for a specific element).

Parameters

styles 
(object) Key-value pairs of CSS properties and their matching values, or (string) the name of a specific CSS property name
value 
(string) Value for a specific CSS property (when styles is a property name)
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining. Notice: When styles is the name of a single CSS property and no value is provided - the method will remove that property and won't return its value (use $("a")[0].styles.color instead).

Like This

// Happy birdies, single property
$("a").css("color", "mileycyrus");
$("a").css("color", "mileycyrus", 0); // Happy birdy (Granular)

// Happy donkeies, multiple properties
$("a").css({
    "color", "selenagomez",
    "letterSpacing": "1.5em"
});
$("a").css({
    "color", "selenagomez",
    "letterSpacing": "1.5em"
}, 0); // Happy donkey (Granular)

// Dough.js performs collection-wide methods,
// so this just removes the property since it
// has no meaning being empty... (sorry if it has)
$("a").css("color");

// This is how you'd retrieve a property's value
$("a")[0].style.color; // Since forever

transform( transformFn[, index ] )

Sets the CSS transform property of every element in the collection (or of a specific element).

Parameters

transformFn 
(string) CSS transform function(s)
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$(".ball").transform("rotateY(90deg)");
$(".ball").transform("rotateY(90deg)", 0); // Granular

translate( [ x, y, z, index ] )

Sets a CSS translate3d() method to every element in the collection (or of a specific element). Notice: This method isn't compatible (yet) with percentage and em values.

Parameters

x 
(integer) Number of pixels to move on the X axis
y 
(integer) Number of pixels to move on the Y axis
z 
(integer) Number of pixels to move on the Z axis
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$(".box").translate(10, 20, 30);
$(".box").translate(10, 20, 30, 0); // Granular
// = translate3d(10px, 20px, 30px)

$(".box").translate(10, 20);
// = translate3d(10px, 20px, 0)
// (No // Granular execution support from now on)

$(".box").translate(10);
// = translate3d(10px, 0, 0)

$(".box").translate();
// = translate3d(0, 0, 0)
// For completely removing the transform
// function use resetTranslate()

Events

on( event, fn[, options, index ] )

Attaches an event-handling method to every element in the collection (or to a specific element). Notice: on() will detach any previously set event handlers configured by on().

Parameters

event 
(string) Name of event to attach the method to
fn 
(function) Method to execute when event is triggered
options 
(object) Key-value pairs of event options. Supported values are isCaptured, a boolean flag for creating an event listener using the capture event processing
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$(".button-heavy").on("click", function() {
    console.log("Bootylicious");
});
$(".button-heavy").on("click", function() {
    console.log("Bootylicious");
}, 0); // Granular

// Using capture event processing
$(".button-heavy").on("click", function() {
    console.log("Bootylicious");
}, { isCapture: true });
$(".button-heavy").on("click", function() {
    console.log("Bootylicious");
}, { isCapture: true }, 0); // Granular

off( event[, index ] )

Detaches a previously set event-handling method from every element in the collection (or from a specific element).

Parameters

event 
(string) Name of event to detach its event handler
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$(".super-form").off("submit");
$(".super-form").off("submit", 0); // Granular

trigger( event[, index ] )

Invokes a previously set event-handling method for every element in the collection (or for a specific element).

Parameters

event 
(string) Name of event to invoke its event handler
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$(".button-heavy").trigger("submit");
$(".button-heavy").trigger("submit", 0); // Granular

click( fn[, index ] )

Attaches an synthesized pointer click event-handling method, which supports both mouse click and touch tap, to every element in the collection (or to a specific element). When being pressed/tapped, a "pressed" CSS selector class is added to the element(s).

Parameters

fn 
(function) Method to execute when event is triggered
index 
(integer) Collection element's index to perform this action on

Returns

The same Dough object for further method chaining.

Like This

$(".button-mister").click(function() {
    console.log("click / tap");
});
$(".button-mister").click(function() {
    console.log("click / tap");
}, 0); // Granular

Requests

$.ajax( options )

Performs an AJAX request using the given options.

Parameters

options 
(object) Key-value pairs of request options.
Supported options:
type 
(string)HTTP request method: "GET" or "POST" (case-insensitive)
url 
(string)URL to send the request to
contentType 
(string)The type of data sent to the server (as HTTP Content-Type header), such as `application/json` (default: `application/json` for GET requests and `application/x-www-form-urlencoded` for POST)
charset 
(string)Request encoding (default: `UTF-8`)
data 
(object)Key-value pairs of properties and their values to post to the server (also good for GET requests)
success 
(function)Method to invoke upon request success. The method is provided with the response data as its argument (when using `application/json` content type, the data is already provided as a parsed object)
error 
(function)Method to invoke upon request error. The method is provided with request HTTP status code as its argument
parseError 
(function)Method to invoke upon JSON parsing error (when using `application/json` content type). The method is provided with the exception object as its argument

Returns

Nothing

Like This

$.ajax({
    type: "get",
    url: "http://my.self/api/songs",
    data: { artist: "Selena Gomez" },
    success: function(data) {
        console.log("I've got " + data.length + " songs in my library, damn!");   
    },
    parseError: function(e) {
        console.log("do I want to handle parse error?", e);
    },
    error: function(status) {
        if (status === 500) {
            console.log("Oopsy");
        } else if (status === 404) {
            console.log("Daisy");
        }
    }
});

$.get( options )

Performs an AJAX GET request using the given options (See ajax() method options for reference).

Parameters

options 
(object) Key-value pairs of request options

Returns

Nothing

Like This

$.get({
    url: "http://my.self/api/songs",
    data: { artist: "Selena Gomez" },
    success: function(data) {
        console.log("I've got " + data.length + " songs in my library, damn!");
    }
});

$.post( options )

Performs an AJAX POST request using the given options (See ajax() method options for reference).

Parameters

options 
(object) Key-value pairs of request options

Returns

Nothing

Like This

$.post({
    url: "http://my.self/api/artist",
    data: {
        name: "Miley Cyrus",
        image: "http://mileycyrus.com/me.jpg"
    },
    success: function(data) {
      // Great success!
 }
});

$.put( options )

Performs an AJAX PUT request using the given options (See ajax() method options for reference).

Parameters

options 
(object) Key-value pairs of request options

Returns

Nothing

Like This

$.put({
    url: "http://my.self/api/artist",
    data: {
        identifier: "miley-cyrus",
        image: "http://mileycyrus.com/me-wrecking-ball.jpg"
    },
    success: function(data) {
      // Great success!
 }
});

$.del( options )

Performs an AJAX DELETE request using the given options (See ajax() method options for reference).

Parameters

options 
(object) Key-value pairs of request options

Returns

Nothing

Like This

$.del({
    url: "http://my.self/api/artist",
    data: { identifier: "hannah-montana" },
    success: function(data) {
      // Great success!
 }
});

$.jsonp( options )

Performs a cross-domain request using JSONP.

Parameters

options 
(object) Key-value pairs of request options.
Supported options:
url 
(string)URL to send the request to
callback 
(string)Name of the method to invoke upon request success
cbParam 
(string)Name of the callback parameter in the request URL (default: "callback")

Returns

Nothing

Like This

function albums_callback(data) {
    console.log("Got data", data);
}

$.jsonp({
    url: "http://my.self/api/albums"
    data: { order: "desc" },
    callback: "albums_callback"
});
// = http://my.self/api/albums&callback=albums_callback&order=desc

// And now with custom callback parameter
$.jsonp({
    url: "http://my.self/api/albums"
    data: { order: "desc" },
    callback: "albums_callback",
    cbParam: "returnCallback"
});
// = http://my.self/api/albums&returnCallback=albums_callback&order=desc

Animation

$.transitionEnd( property, items, fn )

Sets a method to be executed upon the finish of a CSS transition.

Parameters

property 
(string) Name of CSS property to watch for its transition to end. No need to include vendor prefix even when it's required
items 
(HTMLElement) DOM element or any other array/collection (NodeList) of DOM elements which are about to be transitioned
fn 
(function) Method to invoke upon the finish of the transition

Returns

Nothing

Like This

var rows = $(".row");
rows.addClass("transitionable");
// Say .row has "transition: transform .4s ease-in-out"

$.transitionEnd("transform", rows, function() {
    console.log("All 5 elements have transitioned!");
    rows.removeClass("transitionable");
});

rows.addClass("get-down");
// Say it adds "transform: translate3d(10px, 0, 0)"

$.animationEnd( animationName, count, fn )

Sets a method to be executed upon the finish of a CSS animation.

Parameters

animationName 
(string) Name of CSS animation to watch for its playback
count 
(number) Number of elements expected to be animated
fn 
(function) Method to invoke upon the finish of the animation

Returns

Nothing

Like This

var rows = $(".row");

$.animationEnd("bounce", 2, function() {
    console.log("All 2 elements have animated!");
    rows.removeClass("animate-bounce");
});

rows.addClass("animate-bounce");
// Say it adds "animation: bounce .4s ease-in-out"