MooTools makes dynamic DOM manipulation simple. It provides some object oriented wrappers around browser functionality, and ensures cross-browser compatibility with all modern browsers (and even IE6). Lately, I’ve been using MooTools with a couple web applications that are completely rendered in JavaScript.

Rendering the application completely in JavaScript has numerous benefits including:

  • The application behaves similar to a desktop application. It has an asynchronous event-driven interface, and offers much more control over the elements being displayed than simple HTML+CSS.
  • The code is much easier to maintain. JavaScript is a beautiful language. Lets face it, creating an application with HTML is a hack to begin with. HTML was intended as a document markup, not as a mechanism for creating rich interactive interfaces.
  • There are some things you just can’t do with HTML. For instance, passing objects by reference is impossible with inline JavaScript in rendered HTML, and it’s horrible form anyway.

The first thing to do is create a simple HTML landing page that will launch your application.

Example #1: HTML landing page:

<html>
  <head>
    <script type="text/javascript" src="/mootools.js"></script>
    <script type="text/javascript" src="/myapp.js"></script>
  </head>
  <body>
    <div>Loading...</div>
    <script type="text/javascript">
      window.addEvent("domready", function() {
        MyApp.render().replaces($(document.body));
      });
    </script>
  </body>
</html>

Now, in myapp.js you need to define your application. The hook that gets it all started is the render method and it’s expected that this will return a body element. So lets take a look at an example.

Example #2, JavaScript defining the MyApp object:

var MyApp = {
  render: function() {
    var body = new Element("body", {
          html: 'Hello World!'
        });
    body.addEvent('click', function() {
          alert('Click!');
        });
    return body;
  }
};

That’s basically it. If you run this, you’ll see “Loading…” appear while all the JavaScript sources are being downloaded and the DOM tree is constructed in the browser, then it will be replaced with “Hello World!”. When you click on the document body, an alert will pop up saying “Click!”.

Obviously this is an extremely simple example, but this gets you started. From here, you can create a more complex body structure with interactive elements and AJAX calls, and all the good stuff.