A DOM instantiation API designed to tidy up and encapsulate attaching JavaScript to the page


#Intro NPM Build Status Downloads

Attach.js removes dependancy on messy CSS selectors when attaching JavaScript to the page. Attach.js also encapsulates all your DOM "attachments" so that they can easily be reattached when the page is dynamically updated (ie. via AJAX).

I have written Attach.js in pure JavaScript but in the examples I have shown how to use it with jQuery and Mootools.

##The problem Ever thought CSS selectors in your JavaScript were messy or wanted to reatttach JavaScript to the DOM after content was dynamically loaded?

<div class="someSelector">..</div>
<div class="anotherSelector">..</div>
  var x = new SomeThing($('.anotherSelector'));

Pretty messy, and what if the class name changes?


<div data-attach="id">..</div> <!-- Attachments matching id will be added to this element -->
<div data-attach="id2">..</div> <!-- Attachments matching id2 will be added to this element -->
<div data-attach="id id2">..</div> <!-- Attachments matching id and id2 will be added to this element -->
Attach.add('id',function(el){..}); //Add an attachment for id
Attach.add('id2',function(el){..}); //Add an attachment for id2; //Attach to DOM


<div class="someSelector" data-attach="pluginName">..</div>
<div class="anotherSelector" data-attach="SomeThing">..</div>
   new SomeThing($(el));



  • Attach.add(id, callback) {Function} Adds callback for id (matches 'data-attach' value). The callback has one parameter 'el' (DOM element).
  • Attach.remove(id) {Function} Removes callback for id.
  • {Function} Queries DOM and runs callbacks for 'data-attach' values.
  • Attach.engine {Object} Set this to replace the query engine an engine of your choice.
  • Attach.items {Array} List of attachments.

##More detailed examples:

-- This project was inspired by ClientCide's Behavior project and DOM instantiation in Twitter Bootstrap.