JavaScript Utilities

Suit includes a handful of helpful Javascript utilities to help you add common functionality to your apps and plugins.

Using the JavaScript Utilities

There are two ways to use the Foundation utilities that come with Suit: by calling them within the Foundation.utils namespace or by inheriting them in to an object.

Foundation.utils

As long as suit.js has been loaded into the page, you can access any of the Foundation utilities by calling Foundation.utils.{function_name}.

For example, if you type the following into the JavaScript console, it will return a random alphanumeric string.

Foundation.utils.random_str();

Method Inheritance

If you have any plain JavaScript objects, then you can inherit any of the Foundation JavaScript utilities by calling the Foundation.inherit method. To use the inherit method, pass in the object you want to inherit the methods, followed by a space separated string of methods you want to inherit.

// Simple Example
var user = {};
Foundation.inherit(user, 'random_str data_options');

// Advanced Example Person = function() { this.init = function() { Foundation.inherit(this, 'random_str data_options'); } };
var user = new Person(); user.init();

Selector Engine

While jQuery’s selector engine is quite versatile, it can sometimes be a bit slow. Foundation’s "Big S" selector leverages the native browser API by using querySelectorAll(), making it up to 20% faster.

"Big S" can be used as a drop-in replacement for the jQuery $ selector in most cases.

// A simple selector
$('.class #id');

// A bracket selector $('label[for="input1"]');
// A scoped selector $('dd > .content', '#accordion');
// A simple selector
Foundation.utils.S('.class #id');

// A bracket selector Foundation.utils.S('label[for="input1"]');
// A scoped selector Foundation.utils.S('dd > .content', '#accordion');

Throttle & Debounce

Many times when you create a callback, it’s advantageous to add a delay in order to prevent it from being triggered multiple times. Foundation includes two types of callback delays: throttle and debounce.

Throttle prevents a function from being executed more than once every n milliseconds. Throttling is often used in cases where it’s disadvantageous to trigger a callback every time an event is triggered (during a continuous action), but you still want to trigger a reaction while the event is occurring. Examples of this would be reacting to the browser window being resized, or animating an element.

Debounce prevents a function from being executed until it stops being invoked for n milliseconds. Debouncing is often used to prevent an action from being performed twice, such as double clicking a submit button, or to delay an event from occuring accidentially, sunce as an even triggered by hover.

Without Delay

// Button click handler
$('.button').on('click', function(e) {
  // Handle click
});

// Resize function $(document).on('resize', function(e) { // Do responsive stuff });
With Delay

// Debounced button click handler
$('.button').on('click', Foundation.utils.debounce(function(e) {
  // Handle click
}, 300, true));

// Throttled resize function $(document).on('resize', Foundation.utils.throttle(function(e) { // Do responsive stuff }, 300));

Data Options

The data_options method parses a semi-colon delimited set of values in the selected element’s data-options HTML attribue. It’s useful for allowing settings to be passed into a script or plugin from the markup.

<div id="target" data-options="delay:4;color:red;animal:unicorn"></div>
var settings = Foundation.utils.data_options($('#target'));

Media Queries

Media queries are the the backbone of most responsive CSS techniques, though they can be a bit unwieldy to deal with. To make make them easier to deal with, we’ve included two helper methods ( register_media and add_custom_rule), as well as polyfilled the native function matchMedia to work with all the browsers Foundation supports.

Register Media is used to add a new media query to Foundation’s list of JS accessible media queries. These can be found by calling Foundation.media_queries. The method works by appending a meta tag to the head of the document and checking the font-family of the element’s computed styles for the media query string.

Add Custom Rules is a method to add a custom CSS rule as a string to the document. If a media query is passed in the method will apply the style within that media query, otherwise it will be applied globally.

Match Media can be used to check if the browser currently matches the media query passed in as a string. To use the function, call matchMedia() with the media query as an argument, and check the matches property (see example below).

/*
 * Note: The media query string in the font-family property has to be surrounded
 * by slashes to be recognized by Phantom.js
 * Note: Instead of being defined in the CSS, the following style rule could also
 * be added to the document using Foundation.utils.add_custom_rule().
 */
meta.my-mq-custom {
    font-family: "/only screen and (min-width: 40em)/";
    width: 40em;
}
// Register custom media query
Foundation.utils.register_media('custom', 'my-mq-custom');

// Check if the media query is activated if (matchMedia(Foundation.media_queries['custom']).matches){ ... };
// Apply a custom CSS rule to the media query Foundation.utils.add_custom_rule('.js-generated-element { padding-top: ' + element.data('height') + 'px }', 'custom');

Image Loaded

While binding to the document ready event is ususally good enough for most plugins that manipulate the DOM, sometimes you need ALL the content to be loaded before you start calculating things like element sizes. This is especially important with images, which can take while to load and drastically affect the layout of the page, depending on their size.

This can be avoided by using the image_loaded method, which lets you pass in a callback to be executed when an image has completely finished loading. Passing in a jQuery selector that matches multiple images will cause the callback to be executed when all of the images are fully loaded.

Foundation.utils.image_loaded($('img.wait-for-me'), function(){
    console.log('Image Loaded! :)');
});

Random String

The random_str method is a helper for generating random strings of a given length. This method is used by some of the Foundation plugins to ensure a reasonable probability of non-collision for IDs in dynamically generated DOM objects. Note that random_str should not be considered crytographically secure.