--- layout: default nav: docs ---

Intercooler in a Nutshell

Intercooler is very simple to use if you have any web development experience. Anyone reading this should be familiar with anchor tags in HTML:

  <a href="http://intercoolerjs.org/">Get Intercooler</a>

This tells a browser:

"When a user clicks on this link, issue an HTTP GET request to 'http://intercoolerjs.org/' and load the response content into this browser window".

Intercooler builds on this simple concept:

  <a ic-post-to="/button_click">Click Me!</a>

This tells a browser:

"When a user clicks on this link, issue an HTTP POST request to '/button_click' and load the response content into this element".

So you can see that it is very similar a standard anchor link, except that:

  • A different HTTP action is used
  • The request is done via AJAX
  • The response replaces the contents of the element, rather than the entire page

And there you have the core of intercooler. It's a simple idea, but you will be surprised how much you can do with it.

Here is a working version of this example:

Click Me!

Installing Intercooler

Intercooler is just another javascript library, and can be either installed locally with your web application or loaded off our CDN (generously donated by MaxCDN):

  <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
  <script src="https://intercoolerreleases-leaddynocom.netdna-ssl.com/intercooler-0.4.10.min.js"></script>
      

You can always grab the latest code from the Downloads page.

The Core Intercooler Attributes

The core attributes of intercooler are: ic-get-from, ic-post-to, ic-put-to, and ic-delete-from.

Each of these takes a (typically server-relative) URL to issue a request to and then issue an HTTP GET, POST, PUT or DELETE respectively, loading the response content into the element they are on.

Here is an example button that issues a PUT:

  <button ic-put-to="/put_demo">Put Me!</button>

Triggering Intercooler Requests

The core intercooler attributes specify where to make a request, but they don't specify when to do so. By default intercooler will use the "natural" event for an element:

  • For form elements, issue the request on the submit event.
  • For elements matching the JQuery :input pseudo-selector except buttons, issue the request on the change event.
  • For all other elements, including buttons, issue the request on the click event.

For any element you can override the event that triggers an intercooler response by using the ic-trigger-on attribute:

  <a ic-post-to="/mouse_entered" ic-trigger-on="mouseenter">Mouse Over Me!</a>

Mouse Over Me!

If you wish to trigger an intercooler request only when an event has occurred and the value of an element has changed, you can use the changed modifier as well:

    <input type="text" name="text" ic-post-to="/text_changed" ic-trigger-on="keyup changed"
               ic-target="#text-div" placeholder="Enter Some Text"/>
    <div id="text-div"></div>
  

Finally, you can add a delay to the request by using the ic-trigger-delay attribute:

    <input type="text" name="text" ic-post-to="/trigger_delay" ic-trigger-on="keyup changed"
               ic-target="#text-div" ic-trigger-delay="500ms" placeholder="Enter Some Text"/>
    <div id="text-div2"></div>
  

This attribute allows you to wait until a given interval of time has passed before issuing the request. If the event occurs again, the timer will reset and begin waiting again. This is useful, for example, if you want to issue a request when a user pauses in a text input.

Special Events

In addition to the standard JQuery events , Intercooler supports a special event: scrolled-into-view, which is fired when an element is scrolled into view.

This can be useful for implementing UI patterns such as infinite scroll or lazy image loading.

Targeting Other Elements

Sometimes you don't want to replace the content of the element that causes an intercooler request, but rather some other element on the page. For example, you may have a link that, when it is clicked, should replace an entire section of content with the server response.

For these situations you can use the ic-target attribute, which takes a JQuery selector (typically with an element id).

  <a ic-post-to="/target_span" ic-target='#target_span'>Click Me!</a>
  <span id="target_span">You haven't clicked the link next to me...</span>

Click Me! You haven't clicked the link next to me...

Forms & Input Values

Including form data is very simple in intercooler. By default, any element causing an intercooler request will include the serialized version of the nearest parent form. So if the element is a form or is nested within a form the entire form will be serialized and sent up with the request.

Intercooler includes some additional parameters in the request to help you understand which element invoked the request, see Anatomy of an Intercooler Request below for more information.

Including Other Values In Requests

Sometimes you may want to include the values of inputs in a different part of the DOM. To do this, intercooler supports an attribute, ic-include, in which you can specify a JQuery selector to indicate what other elements to serialize in the request or you can specify a JSON object of name/value pairs to include in the request.

Submit the form above...

Polling

A common pattern in web development is to have a page poll a URL for updates. Until the day comes when push technologies are available widely, this technique is the best way to dynamically update a UI without a specific client-side event happening.

Intercooler supports an attribute, ic-poll, which tells an element to poll whatever URL is associated with it on a given interval. This attribute can be of the form "10s" or "100ms", where "s" indicates seconds and "ms" indicates milliseconds.

Below is an example:

          <span ic-poll="2s" ic-src="/poll_example">
            This span will poll the server every two seconds...
          </span>
        
This span will poll the server every two seconds...

Configuring Polling Behavior

Intercooler supports a few ways to modify polling behavior. The first is the ic-poll-repeats attribute, which you can use to limit the number of times a intercooler will poll for a given element.

A second way is to use the X-IC-CancelPolling response header, which will cancel polling of an element. See the Anatomy of an Intercooler Response section for more details on intercooler response headers.

Progress Indicators

An important but often overlooked aspect of UI design is indicating when a remote request is in flight. Modern browsers have unfortunately made the situation worse for normal web requests by making the request indicator less and less obvious, for what I can only assume are aesthetic considerations.

AJAX requests have never had a proper indicator mechanism, so it is up to us to build one. Intercooler provides tools to make this easy.

The ic-indicator Attribute

The first tool available is the ic-indicator attribute, which specifies a selector of an indicator element in the DOM. This element will be made visible during the life of the intercooler request, and hidden afterwards.

Here is an example:

          <button ic-post-to="/indicator_demo" ic-indicator="#demo-spinner">Click Me!</button>
          <i id="demo-spinner" class="fa fa-spinner fa-spin" style="display:none"></i>
        

This attribute can be specified on a parent element if you want a group of elements to share the same indicator.

The ic-indicator Class

Another option is to use the ic-indicator class on an element that is a child of the element issuing the intercooler request.

Here is an example:

          <button ic-post-to="/indicator_demo2">Click Me!
            <i class="ic-indicator fa fa-spinner fa-spin" style="display:none"></i>
          </button>
        

This is less code and is better UX for some situations, but has the disadvantage that if the parent element is replaced the indicator will be removed, causing what can appear to be an abrupt transition.

Disabling Elements

By default, intercooler will apply the disabled class to the element that triggers an intercooler request. This can be used to give a visual hint to the user that they should not click or otherwise trigger the request again, and is Bootstrap-friendly.

In the above demos you will see that the button greys out during the request, which is due to Bootstrap's handling of this CSS class.

Element Transitions

You can control the way that elements are swapped into the DOM with intercooler's transition support.

By default, intercooler uses JQuery's fadeFast transition to fade out old elements and fade in new elements. This is a nice visual queue for users.

You can override this behavior in a few different ways:

If you wish to override the behavior for a specific element, you can use the ic-transition attribute:

          <button ic-post-to="/transition_demo" ic-transition="none">Click Me!</button>
        

Here we use the none transition, for immediate replacement.

If you wish to override the behavior globally, you can use the Intercooler.defaultTransition() method in javascript:


          Intercooler.defaultTransition("none");
        

Currently the valid transitions are "fadeFast" and "none"

In a future intercooler release we may move to pure CSS transitions.

Timed Removal Of Elements

A common pattern in AJAX applications is to "flash" an element after a request: show the element for a bit then remove it from the DOM. Intercooler includes the ic-remove-after attribute for this situation which, like ic-poll, can take the form "2s" or "1500ms". Once the given amount of time has elapsed, the element will be removed from the DOM, using the applicable transition for the element.

Here is an example:

Click Me!

History Support BETA

Intercooler provides simple history support for AJAX calls. This functionality is currently experimental, but is usable and unlikely to change dramatically going forward.

If you want an intercooler call to push its target URL into the location bar and create a history element, simply add the ic-push-url attribute to the element and ensure that the target of the element has a stable HTML id.

Here is an example:

    <a id="hist-link" ic-post-to="/history_demo" ic-push-url="true">Click Me!</a>
  
Click Me!

Sometimes whether or not you want to update the location of the page will be dependent on the result of the intercooler request. In that case, rather than using the ic-push-url attribute, you can use the X-IC-PushURL header, outlined below in the Intercooler Response section.

Note: This is one area where intercooler leverages some relatively recent web technologies that may not be present on older browsers. Namely, it uses Web Storage and the JSON object, both of which are not available in various older browsers. If you wish to maintain maximum compatibility with your intercooler website, you should not use the history support.

Anatomy Of An Intercooler Request

Intercooler requests are fairly straight forward HTTP requests, but they do have a few non-standard aspects that help you out.

Special Parameters

In addition to the form serialization discussed above, intercooler requests include a few additional parameters in every AJAX request:

Parameter Description
ic-request This will always be true for intercooler requests.
_method Because not all browsers support PUT and DELETE requests in AJAX, intercooler uses the Rails convention and adds a _method parameter to the request whose value will be the HTTP Method type (e.g. DELETE).
ic-last-refresh This is a timestamp of the last time the target element was refreshed. This can be used to calculate time-sensitive UI updates (e.g. appending to a list of messages.)
ic-fingerprint The SHA256 fingerprint of the current content. This can be used to avoid sending down unnecessary updates, caching, etc.
ic-element-id The HTML id of the element that caused the request. This helps you differentiate between different buttons that may hit the same URL, for example.
ic-element-name The HTML name of the element that caused the request. This helps you differentiate between different buttons that may hit the same URL, for example.
ic-id The internal intercooler ID of the element that caused the request.
ic-current-url The current URL of the page.

Special Headers

Intercooler also includes a few extra request headers:

Header Description
X-IC-Request Set to true
X-HTTP-Method-Override Set to the HTTP Method type (e.g. DELETE) for the request, to communicate the actual request type to the server if it cannot be directly supported by the client.

Anatomy Of An Intercooler Response

Intercooler responses are HTML fragments. Here is an example of some content:

  <div>
    Here Is Some Content!
  <div>
      

This would be swapped in as the body of the element that initiated the request.

The returned content can, of course, contain Intercooler attributes itself, which will be all wired up.

No-Op Responses

Intercooler interprets an empty body or a single whitespace character in a request as a No-Op, and will do nothing in response. If you want to replace an element with only whitespace, return at least two whitespaces worth of content.

Intercooler Response Headers

Not all UI needs can be captured via pure element swapping. Occasionally you may need to invoke a client side event, let other elements know to refresh themselves, redirect the user entirely, and so on.

To handle these situations, intercooler supports custom HTTP headers. These headers can be used to instruct intercooler to perform additional work in addition to swapping in the returned HTML.

Here is a table of the response headers intercooler supports:

Header Description
X-IC-Trigger Allows you to trigger a JQuery event handler on the client side
X-IC-Trigger-Data Allows you to pass JSON data to the event triggered by the X-IC-Trigger header. Note that extraParameters passed to the event are treated as an argument list if the data is a JSON array. See the JQuery trigger() documentation for more information.
X-IC-Refresh A comma separated list of dependency paths to refresh.
X-IC-Redirect Causes a client-side redirect to the given URL.
X-IC-Script Allows you to evaluate arbitrary javascript.
X-IC-CancelPolling Cancels any polling associated with the target element.
X-IC-Open Opens a new window at the given location.
X-IC-PushURL Sets a new location for the page and saves the history of the element being replaced.
X-IC-Transition Overrides the elements normal transition.
X-IC-Remove Removes the target element.

Dependencies In Intercooler

Intercooler has a novel mechanism for managing inter-element dependencies which builds on the concept of REST-ful URLs.

Intercooler uses server path relationships to encode dependencies. The idea is straight forward and natural if you have are familiar with REST-ful URL schemas:

If an element reads its value (i.e. issues a GET) from a given server path, and an action updates that path (i.e. issues a POST to it), refresh the element after the action occurs.

So, as a simple example, consider this button and div:


  <button ic-post-to="/example/path">A Button</button>

  <div ic-src="/example/path">A Div</div>
     

Here the div depends on the button, because they share a path with one another. When Intercooler issues a POST to the given path (on a user click), upon completion, it will issue a GET to the same path, and replace the div with the new content, if it is different.

What Paths Depend On What?

It's all very simple when the POST and GET are to the same path, but what if they aren't? What if the post is to /jobs/2341/start and the get is from /jobs/2341? Or vice-versa?

Our answer is as follows:

Two server paths express a dependency if either path is the starting path of the other.

So:

Path Updated Path Read Dependency?
/foo /bar NO
/foo /foo YES
/foo/bar /foo YES
/foo /foo/bar YES
/foo/doh /foo/bar NO

Explicit Dependencies

The dependencies above are managed implicitly by Intercooler and, with reasonable layout of your restful URLs, should handle many cases. However, there may be times when you need to express dependencies explicitly. In Intercooler, you can use the ic-deps attribute to express additional paths that an element depends on.

Intercooler Events

Intercooler fires JQuery-style events that can be listened for. Here is a table of the events that are fired:

Event Description
log.ic(evt, msg, level, elt) Event fired when log messages occur internally in intercooler (can be used to debug specific DOM elements.)
beforeHeaders.ic(evt, elt, xhr) Triggered before intercooler headers are processed.
afterHeaders.ic(evt, elt, xhr) Triggered after intercooler headers are processed.
beforeSend.ic(evt, elt, data, settings, xhr) Triggered before sending an intercooler AJAX request to the server. The second argument to the event is the data hash, and can be added or removed from to change the values sent to the server.
success.ic(evt, elt, data, textStatus, xhr) Triggered after a successful intercooler request is received
error.ic(evt, elt, status, str, xhr) Triggered after an error occurs during an intercooler request
complete.ic(evt, elt, data, status, xhr) Triggered after an intercooler request completes, regardless of status. This event is triggered on the body tag.
onPoll.ic(evt, elt) Triggered before a poll request is dispatched
handle.onpopstate.ic(evt) Triggered when intercooler handles an onpopstate event. Triggered on the document body.

Example

Here is some code that uses the BlockUI library to block the UI when an intercooler request is in flight:

        $(function(){
          $('#blocking-button').on('beforeSend.ic', function(){
            $.blockUI();
          }).on('complete.ic', function(){
            $.unblockUI();
          });
        })
      

Event Attributes

Javascript can also be invoked with the following attributes: ic-on-beforeSend, ic-on-success, ic-on-error, and ic-on-complete.

Here is the same demo as above using attributes rather than a JQuery event handler:

These attributes can be placed on parent elements if you want to specify a behavior for an entire secion of a DOM tree.

Debugging Intercooler

Intercooler comes with an integrated debugger. You can launch the debugger by either invoking the Intercooler.debug() method or by passing a true value in for the ic-launch-debugger parameter to a page.

The debugger consists of three tabs: "Elements", "Logs" and "Errors".

"Elements" has a clickable list of active elements on the page. When you click on one of the items in the list, it will be highlighted on the page, and intercooler-related details will be shown about it.

"Logs" has the intercooler log stream, including clickable links to the elements that caused each message.

"Errors" will show any errors that intercooler detects (e.g. bad targets on an element).

You can launch the debugger on this page by clicking this button:

If you would like, you can capture the intercooler log event if you want to see the low level events that are driving intercooler:

        $(function(){
          $(window).on('log.ic', function(evt, msg, level, elt){
            console.log(msg);
          });
        })
  

Using Intercooler from Javascript

Intercooler does not have a large javascript API because it is intended to sit in the background, issuing and processing requests. Events and dependencies can be used to handle almost all dynamic situations that intercooler is appropriate for.

There are, however, a few methods you can invoke on the global Intercooler object:

Method Description
Intercooler.defaultTransition(name) Lets you set the default transition to use
  Intercooler.defaultTransition('none');
Intercooler.processNodes(root) Will process all intercooler attributes on the given root.
Intercooler.refresh(eltOrPath) If the argument is an element, it will issue a new AJAX request. If it is a string path, it will issue a request for all dependent elements.

Conclusion

And that's it!

Not a ton to it, which is kind of the point: you can build surprisingly rich UIs with this simple and easy to understand tool, and you can do it incrementally in the areas that matter the most for your users.

"The minimum complexity compatible with user joy."