Menu

Adaptive.js API

Browse the commands in the Adaptive.js software suite to program your mobile adaptation.

Adaptive Defaults Internationalization

Require.js Plugin ResizeImages Router
Utils View Processor

Adaptive

Adaptive.disable(url)

The disable function disables the Adaptive.js transformations in your current session. It sets a cookie that stops Adaptive.js from loading.

Input
Parameter Name Parameter Type Description
url String optional Where the page should redirect after disabling adaptation. If the function is called before we have rendered out a new page (in capturing mode) the URL parameter is ignored and we simply call Adaptive.restore().

Code Sample:

<a href="#" onclick="Adaptive.disable()">Back to desktop</a>


Adaptive.init(callback)

The init function kicks off adaptation, prevents all resources from downloading on the page, and passes the original document to your callback.

Input
Parameter Name Parameter Type Description
callback Function optional A function to call after the current command finishes execution. Function which gets executed once the init function is finished. The callback is passed the original document.

Code Sample:

Adaptive.init(function(doc){
    // Render the original document.
    Adaptive.renderPage(doc.documentElement.outerHTML);
});


Adaptive.renderPage(htmlString)

The renderPage function rewrites the original document with the one that is provided by the htmlString argument.

Input
Parameter Name Parameter Type Description
htmlString String The HTML representation of the adapted page.

Code Sample:

Adaptive.renderPage('New Document');


Adaptive.restore()

The restore function reverts your page to display the original source document.

Code Sample:

// Use the Router to resolve a captured document.
var view = router.resolve(capturedDocument);

// If a view is not found, use the restore function // to bring back the desktop site. if (!view) { return Adaptive.restore(); }

Defaults

Defaults.getContext(document)

The getContext function returns a context with a group of default keys such as buildDirectory.

Input
Parameter Name Parameter Type Description
document String The document which should be used to determine defaults.

Code Sample:

var context = Defaults.getContext(document);

(Internationalization) I18n

new I18n(defaultLocale, dictionary)

The constructor creates a new instance of an i18n translator object.

Input
Parameter Name Parameter Type Description
defaultLaocale String The locale which should be the default when doing lookups
dictionary Object The dictionary used to look up translations

Code Sample:

var translator = new I18n('en-US', dictionary);


I18n.prototype.setDefaultLocale(locale)

The setDefaultLocale function sets the default locale to look at if no current locale is set.

Input
Parameter Name Parameter Type Description
locale String The locale which should be the default when doing lookups

Code Sample:

translator.setDefaultLocale('en-CA');


I18n.prototype.setLocale(locale)

The setLocate function sets the current locale to use when doing translations.

Input
Parameter Name Parameter Type Description
locale String The locale to use as the current locale.

Code Sample:

var translator = new I18n('en-US', dictionary);
// Set the locale to Germany.
translator.setLocale('de-DE');


I18n.prototype.translate(key)

The translate function returns the matching key for the current locale from the i18n dictionary. If no key was found, the key from the default locale will be returned. If no key in the default locale is returned, a message is returned saying the key could not be found.

Code Sample:

var translator = new I18n('en-US', dictionary);

translator.setLocale('de-DE') translator.translate('hello'); // Returns 'Guten Tag'

Require Plugins

Modules are loaded with require.js in the AMD format.

Require.js Dust Plugin (Adaptation and UI)

You can also load templates into Adaptation views and UI scripts using the dust plugin provided with Adaptive.js. Templates live in the adaptation/templates folder for the adaptation, and the assets/templates folder for UI. They are loaded similarly to modules, with the addition of dust! before the module name to indicate that they need to be processed with the require.js dust plugin.

The dust plugin returns a function that you can use to process the markup from the template. It takes two arguments.

Like with modules, remember not to include the .dust after filenames.

Input
Parameter Name Parameter Type Description
context Data that you want to pass to the template. Dust tags in the template like foo are replaced with the values provided here.
callback A callback function that processes the returned content. The first parameter contains any errors encountered during rendering, and the second contains the HTML to be rendered.

Code Samples:

In the Adaptation:

define([
    '$',
    'views/base',
    'dust!templates/home'
],
function($, BaseView, template) {
    return {
        template: template,
        extend: base,
        // ...
    }
});

In the UI:

define(
    ['dust!templates/myTemplate'],
    function(myTmpl) {
        myTmpl({ foo: 'bar' }, function(err, html) {
            console.log('HTML :', html);
        });
    });

Require.js External Plugin (UI)

In addition to loading new modules, you can reuse modules from the adaptation using the external plugin for require.js. For example, let's say you have a template _viewPartial that you would like to use in both the adaptation in the UI. You would include the partial in your adaptation view, and then in your UI scripts, you would indicate to Adaptive.js that you have already built that template, and request that it be loaded into the UI without including it in the UI scripts again: [old code sample]

Note that with the second module in the dependency array, here we've also added the dust! to indicate that this is a dust template and not a module that we're reusing.

Code Sample:

define(
    ['external!someModule',
    'external!dust!templates/partials/viewPartial'],
    function(someModule, viewPartial) {
        someModule();
        viewPartial({ foo: 'bar' }, function(err, html)) {
            console.log('HTML: ', html);
    });
});

<!-- Ends the External plugin table -->

ResizeImages

ResizeImages.getImageURL(url, options)

The getImageURL function returns the URL that would be set as the value of the src as above.
This function is provided as a utility only for dealing with special cases such as CSS background images or lazy loader code. If you wish to resize images represented by an img element, use the resize function instead.

Input
Parameter Name Parameter Type Description
url String A string containing the original image URL that needs resizing.
options Object An object that contains the image resize settings to apply. The maxWidth and maxHeight parameters are in raw device pixels here and do not have a default value.

Output
Type Description
String The URL to set as the value of the src above.

Code Samples:

In the Adaptation:

var productImage = document.querySelector('.product-image')[0];
var originalURL = productImage.src;
var resizedURL = ResizeImages.getImageURL(originalURL, {
    cacheHours: 1
});
productImage.src = resizedURL;
// http://ir0.mobify.com/project-mobify-com/c1/
// http://www.mobify.com/static/i/home/hero-2up.png

ResizeImages.processOptions()

The processOptions function returns an object that has the default image options set. The image width and the height are different for each device type for image display optimization.

Output
Type Description
Object The object that has the default image options set for the device.

Code Sample:

ResizeImages.processOptions();

// returns (for an iPhone 5 visiting the site http://www.example.com/): // { // proto: '//', // host: 'ir0.mobify.com', // projectName: "oss-www-example-com", // sourceAttribute: "x-src", // targetAttribute: "x-src", // webp: false, // onerror: 'ResizeImages.restoreOriginalSrc(event);' // maxWidth: 640 // }

ResizeImages.resize(images, options)

The resize function rewrites the src tag of every image in the images array with the URL of the resized image.

Input
Parameter Name Parameter Type Description
images Array An array of img and/or picture elements
options Object An object containing the image resize settings to apply as above, except that the maxWidth and maxHeight parameters are in raw device pixels here and do not have a default value.

  • cacheBreaker: A string added to the final image URL to break the cache.
  • cacheHours: Sets the length of time (in hours) for the image(s) to be cacheable, both on the CDN and in the browser. Defaults to 8 hours.
  • devicePixelRatio: A number representing the ratio of CSS pixels to real device pixels, Exposed for testing purposes. Defaults to window.devicePixelRatio.
  • format: A string designating the format of resized image. Values: 'jpg', 'png', 'webp', 'q' (original format). Defaults to no change of format. Note: Non-animated GIFs are converted to PNG and animated GIFs cannot have their format changed.
  • maxHeight: Maximum height of the resized image, in CSS pixels. Must use in conjunction with maxWidth.
  • maxWidth: Maximum width of the resized image, in CSS pixels. Defaults to device width.
  • quality: An integer from 1-100. Sets the quality of the output image. The original image must be a jpg or webp image, or the format must be set to jpg or webp for this to have any effect.
  • resize: A boolean that controls whether to scale the images. If 'false', the images are served through the image resizer CDN and possibly re-encoded, but not resized. Defaults to 'true'.
  • sourceAttribute: The attribute to get the source value from. Defaults to 'x-src'.
  • targetAttribute: The attribute to set with the resized URL. Defaults to 'x-src'.
  • Code Sample:

    var images = document.querySelectorAll('img');
    ResizeImages.resize(images, {
        format: 'jpg',
        quality: 80
    });

    Profiles:

    Some options presets are provided on ResizeImages.profiles

  • SHORT_CACHE sets a 2 hour cache lifetime on the resulting asset, for images that might change without changing URL.
  • LONG_CACHE sets a 1 week cache lifetime for assets that will remain valid for longer periods.

  • You can combine these profiles with your own options objects like so:

    var options = Utils.extend({
        yourOptions
    }, ResizeImages.profiles.SHORT_CACHE);

    Best Practices:

    Be cautious when using this API — any assets used with it will be served with caching headers, as such, it is important to be sure that caching them will not be problematic.

    Image types that should not be used with this API:

  • Tracking pixels
  • Dynamically generated images (e.g. counters)
  • Images that will change, but whose URL cannot be changed
  • Router

    Router.Ignore

    The Ignore constant is used in conjunction with a function match that returns a truthy value. Use this constant to skip adaptations and to fall back to the desktop site.

    Code Sample:

    router.add(function() {
        // To force the ignore, the function match returns a truthy value.
        return $('.my-page-to-ignore').length;
    }, Router.Ignore)


    Router.prototype.add(function, view)

    The add function adds a route to the router. The route is matched if the function evaluates to a truthy value. When the route is matched, the resolve method returns the router.

    Input
    Parameter Name Parameter Type Description
    function Function Function which returns true when the route should match.
    view Object The view to render if the matching function returns true.

    Output
    Type Description
    Object The router.

    Code Samples:

    Single call:

    router.prototype.add(Router.selectorMatch('body.home'), HomeView);

    Chaining: The add function returns the router itself, so it supports function chaining.

    router.add(Router.selectorMatch('body.home'), HomeView)
        .add(Router.selectorMatch('.cartItem'), CartView)
        .add(Router.urlMatch('/order/confirmation'), ConfirmationView);


    Router.prototype.getRoutes()

    The getRoutes function returns an array with all the routes that have been added to the router. Use this function for debugging or doing more complex things with the router.

    Output
    Type Description
    Array The array of routes that have been added to the router.

    Code Sample:

    router.add(Router.selectorMatch('body.home'), HomeView)

    router.getRoutes(); // returns [{func: function(){...}, view: HomeView}]


    Router.prototype.resolve(document)

    The resolve function evaluates each route against the provided document until a route is matched. The function returns the view associated with the matched route, or a blank to fall back to the desktop site version.

    Input
    Parameter Name Parameter Type Description
    document Object The document to run the matching criteria on.

    Output
    Type Description
    Object The view object, or a blank.

    Code Sample:

    var view = router.resolve(capturedDocument);
    // If the view is blank, fall back to the desktop site.
    if (!view) {
        console.error('No routes were matched. Render the original document.');
        Adaptive.restore();
        return;
    }


    Router.selectorMatch(selector)

    The selectorMatch function returns a function that checks if the given selector is in the document. The returned function evaluates to true or false.

    Input
    Parameter Name Parameter Type Description
    selector String Selector to check for.

    Output
    Type Description
    Function The function to evaluate to a Boolean value.

    Code Sample:

    Router.selectorMatch('body.home')


    Router.urlMatch(urlExpression)

    The urlMatch function returns a function which checks if the urlExpression parameter is in the current page's URL. The returned function evaluates to true or false. Pass the urlFragment parameter as a String or as a regular expression. The String is converted to a regular expression if it isn't one already.

    Input
    Parameter Name Parameter Type Description
    urlExpression String The portion of the URL to match in document.URL

    Output
    Type Description
    Function The function to evaluate to a Boolean value.

    Code Sample:

    Router.urlMatch('/category/muffins')

    Router.pathMatch(urlExpression)

    The pathMatch function returns a function which checks if the pathExpression parameter is in the current page's URL, ignoring query string and hash. The returned function evaluates to true or false. Pass the pathExpression parameter as a String or as a regular expression. The String is converted to a regular expression if it isn't one already.

    Input
    Parameter Name Parameter Type Description
    pathExpression String The portion of the URL to match in document.URL

    Output
    Type Description
    Function The function to evaluate to a Boolean value.

    Code Sample:

    Router.pathMatch('/category/muffins')

    Utils

    Include this package in the require portion of your JavaScript file with the adaptivejs/utils line.

    Utils.absolutify(url)

    The absolutify function takes a relative or an absolute URL and absolutizes it relative to the current document's location.

    Input
    Parameter Name Parameter Type Description
    url String The URL, or URL fragment to absolutize.

    Code Sample:

    // We're on http://adaptivejs.mobify.com/
    console.log(Utils.absolutify('v2.0/'));
    // logs http://adaptivejs.mobify.com/v2.0/


    Utils.clone(object)

    The clone function returns a new object which is a copy of the passed object.

    Input
    Parameter Name Parameter Type Description
    object Object The object to copy.

    Output
    Type Description
    Object The clone of the original object.

    Code Sample:

    var stormTrooper2 = Utils.spawn(stormTrooper);


    Utils.domIsReady()

    The domIsReady function returns true or false based on the document.readyState == interactive document state.

    Output
    Type Description
    Boolean True if the DOM is ready.


    Utils.extend(targetObject, sourceObject)

    The extend function adds all properties of the source object onto the target object. The function returns the target object.

    Input
    Parameter Name Parameter Type Description
    targetObject Object The object to which the properties are assigned to.
    sourceObject Object The object from which to copy the properties.

    Output
    Type Description
    Object The target object that has its properties extended from the source object..

    Code Sample:

    var newChild = Utils.extend(child, parent);


    Utils.getAdaptiveBuild()

    The getAdaptiveBuild function returns a String of the src source attribute of the Adaptive.js build script.

    Output
    Type Description
    String The source attribute of the Adaptive.js script build.

    Code Sample:

    console.log(Utils.getAdaptiveBuild());
    // logs http://localhost:8080/build/adaptive.js


    Utils.getAssetUrl(path, [basePath], [cacheBreaker])

    The getAssetUrl function returns a String that contains the URL of an asset given the path, base path, and cache breaker. Provide the cache breaker as an argument, a hash of the file contents, or a build date. The function appends a random set of characters to make the URL unique every time.

    Input
    Parameter Name Parameter Type Description
    path String The path to the asset.
    baseURL String optional The origin part of the URL for the asset.
    cacheBreaker String optional The cache breaker to use in the asset URL.

    Output
    Type Description
    String The URL of the the asset.

    Code Sample:

    var url = Utils.getAssetUrl('css/stylesheet.css'));
    // Returns http://localhost:8080/css/stylesheet.css?a1s2d3f4


    Utils.getBuildOrigin()

    The getBuildOrigin function tells you where the Adaptive.js build file is served from. The function returns a String of the origin part of the Adaptive.js build URL. Use this function to reference a build image or a JavaScript file.

    Output
    Type Description
    String The origin portion of the Adaptive.js build URL.

    Code Sample:

    // If we're on http://localhost:8080/adaptive.js
    console.log(Utils.getBuildOrigin());
    // Logs http://localhost:8080/

    // If we're on http://cdn.mobify.com/projects/foo/mobify.js console.log(Utils.getBuildOrigin()); // Logs http://cdn.mobify.com/projects/foo/


    Utils.getDoctype([document])

    The getDoctype function returns a String for the type of the provided document. If no document is passed in, the current document is used.

    Input
    Parameter Name Parameter Type Description
    document Object optional The document for which to check the type.

    Output
    Type Description
    String The DOCTYPE attribute tag.

    Code Sample:

    console.log(Utils.getDoctype());
    // logs "<!DOCTYPE HTML>"


    Utils.getMetaViewportProperties()

    The getMetaViewportProperties function returns an object that represents the parsed content attribute of the viewport meta tag. It returns false if no viewport meta tag is present.

    Output
    Type Description
    Object or Boolean An object that contains the attribute of the viewport meta tag. False if there is no viewport meta tag.

    Code Sample:

    var viewport = Utils.getMetaViewportProperties();
    // viewport = {
    //     width: "device-width",
    //     initial-scale: "1.0",
    //     maximum-scale: "1.0",
    //     user-scalable: "no"
    // }


    Utils.getPhysicalScreenSize()

    The getPhysicalScreenSize function returns an object with the physical screen's width and height of the device in pixels as object keys.

    Output
    Type Description
    Object An object whose keys represent the width and height of the physical device in pixels.

    Code Sample:

    var screenSize = Utils.getPhysicalScreenSize();
    // screenSize = {
    //     width: 1440,
    //     height: 900
    // }


    Utils.isDebug()

    The isDebug function checks the document.cookie to check whether the site is in debugging mode. Use this when you only want to execute a piece of code in testing mode.

    Output
    Type Description
    Boolean A Boolean value that indicates true when the site is in debug mode.

    Code Sample:

    console.log(Utils.isDebug());
    // Logs true after going through http://preview.mobify.com


    Utils.isFunction(value)

    The isFunction function returns true if the passed value is a function.

    Input
    Parameter Name Parameter Type Description
    value Object The object to investigate.

    Output
    Type Description
    Boolean A Boolean that indicates true if the argument passed to the function is itself a function.

    Code Sample:

    //returns true
    Utils.isFunction(function(){return 'I am a function';});


    Utils.isObject(value)

    The isObject function returns true if the argument passed to it is an object. This function is mostly used with the Router.

    Input
    Parameter Name Parameter Type Description
    value Object The object to investigate.

    Output
    Type Description
    Boolean A Boolean that indicates true if the argument passed to the function is an object.

    Code Sample:

    // returns true
    Utils.isObject({});


    Utils.isRegExp(value)

    The isRegExp function returns true if the argument passed to it is a regular expression.

    Input
    Parameter Name Parameter Type Description
    value Object The object to investigate.

    Output
    Type Description
    Boolean A Boolean that indicates true if the argument passed to the function is a regular expression.

    Code Sample:

    Utils.isRegExp(/realRegExp/);
    // Returns true

    Utils.isRegExp('/notRexExp/'); // Returns false


    Utils.keys(object)

    The keys function returns an array of each of the objects keys that are part of the object itself, and not inherited from the object's prototype.

    Input
    Parameter Name Parameter Type Description
    object Object The object from which to return the keys.

    Output
    Type Description
    Array An array of the object's keys.

    Code Sample:

    var obj = {'a': 'aardvark', 'b': 'basilisk'}
    console.log(Utils.keys(obj));
    // prints ['a', 'b']


    Utils.matchMedia(mediaQuery)

    The matchMedia is a Polyfill function that returns a MediaQueryList object which stores the results of running the provided media query. The match media functionality may not be implemented in every browser, so we use our own version of the function to ensure that it always executes.

    Input
    Parameter Name Parameter Type Description
    mediaQuery String The media query to run against the page.

    Output
    Type Description
    Object The object that stores the media query matches.

    Code Sample:

    console.log(Utils.matchMedia("(min-width: 400px)").matches);
    // logs true


    Utils.outerHTML()

    The outerHTML function is a Polyfill function which returns the serialized htmlElement piece of HTML, which is the DOM as a String, and its descendants. Use this function to replace some of the content with a regular expression or with the String representation of a part of the document. This Polyfill function ensures that the method works for browsers which don't have the outerHTML function implemented.

    Output
    Type Description
    String The HTML around the selected element.

    Code Sample:

    <!-- In the original document HTML: -->
    <div id="header"><p>content</p></div>
    

    // In your JavaScript code:
    var el = document.getElementById('#header');
    console.log(Utils.outerHTML(el));
    // logs <div id="header"><p>content</p></div>


    Utils.removeBySelector(selector, [document])

    The removeBySelector function removes all elements that match the provided selector from the provided document. The function returns an array of DOM elements that were removed. If no document is specified, the elements are removed from the current document.

    Input
    Parameter Name Parameter Type Description
    selector Object The selector which matches the elements to remove.
    document Object optional The document from which to remove the elements. If none is specified, the current document is used.

    Output
    Type Description
    Array The list of DOM elements that were removed from the document.

    Code Sample:

    // Removes all scripts from the current document
    var scripts = Utils.removeBySelector('script');


    Utils.removeElements(elements, [document])

    The removeElements function removes all elements in the list from the provided document. If no document is specified, the elements are removed from the current document.

    Input
    Parameter Name Parameter Type Description
    elements Array The array of elements to remove.
    document Object optional The document from which to remove the elements. If none is specified, the current document is used.

    Code Sample:

    // Removes all scripts from the current document
    var scripts = $('script');
    Utils.removeElements(scripts);


    Utils.supportsLocalStorage()

    The supportsLocalStorage function returns true if the device supports local storage for persistent storage between pages. Use this function to store pages and to retrieve them later instead of requesting them from the site. An example on the site of this is for checking items that are currently in the cart.

    Output
    Type Description
    Boolean Returns true if the device supports local storage.

    Code Sample:

    
    if (Utils.supportsLocalStorage()) {
        // Store the basket data to localStorage
        localStorage.setItem('basketData', data);
    }


    Utils.values(object)

    The values function returns an array of the values that correspond to properties of the object. It does not include properties inherited from a parent object. It is the opposite of the Utils.keys function.

    Input
    Parameter Name Parameter Type Description
    object Object The object whose values to return.

    Output
    Type Description
    Array The properties of the object.

    Code Sample:

    var obj = {'a': 'aardvark', 'b': 'basilisk'}
    console.log(Utils.keys(obj)); // prints ['aardvark', 'basilisk']

    View Processor

    View.evaluateContext(view, defaultContext)

    The evaluateContext function takes a view and an object with any default context keys to add. It returns a context object. The returned context is made up of the view's context as well as the contexts from all the includes and its parent view. Any keys that are functions are evaluated.

    Input
    Parameter Name Parameter Type Description
    view Object The view whose context to combine with the defaultContext
    defaultContext Object The object with the default context keys to add to those of the view context.

    Output
    Type Description
    Object The context that contains the context of the view, its parent view, and that any includes.

    Edit in GitHub