This ‘article’ was aimed at helping webmasters, programmers and designers in 2008 who already had a rudimentary understanding of javascript and DOM programming in cementing their knowledge and getting a solid base for building browser apps in the future. Keep in mind that a lot has changed since in terms of best practices and features, this article should be considered defunct. For illustration purposes, it is using the MooTools framework but this does not mean it’s the only sensible choice.
I have been posting a fair bit on DigitalPoint’s javascript forums recently and was amazed to discover (well, not really) the huge amounts of people that struggle to get basic javascript bits and bobs working. Adding a javascript framework won’t necessarily fix that all of these problems but a good half of them (at least) will get ‘nearly there’. It also proven to improve manhood tenfold…
So, what is a javascript framework anyway?
In a nutshell: a library of pre-written javascript controls, functions and methods that make it easier for the developer to quickly and accurately produce cross browser compliant code. Example popular frameworks are: YUI, ExtJS, Prototype, MooTools and of course, jQuery. There are also several smaller frameworks around – have a look on ajaxian for a recent rundown of the relative unknowns (like Capuccino)
Yeah, and? What do I need all these libraries for?
Selectors
making sure you can access any and all of your DOM elements at your fingertips
Typically, frameworks provide all sorts of shortcuts for accessing elements within the DOM. These are called selectors and are similar to CSS selectors. Example:
<div id="mydiv" class="myclass" rel="89">click me</div> <div id="mydiv2" class="myclass" rel="90"><a href="#">null link #0</a></div> <span id="myspan" class="myclass" rel="89">hello world 3</span> <a href="#">null link #1</a> <a href="#">null link #2</a> <a href="/index.php">normal link</a> <input id="name" type="text" class="textfield" /> <input id="surname" type="text" class="textfield required" />* <textarea id="message" class="required"></textarea>*
… and mootools selectors on the above
var div = $("mydiv"); // just reference by id, same as document.getElementById("mydiv"); // get an array of all elements that are 'myclass' (mydiv, mydiv2, myspan) var elsArray = document.getElements(".myclass"); // get an array of div elements that are 'myclass' (mydiv, mydiv2) var elsArray = document.getElements("div.myclass"); // get an array of elements that are myclass and rel == 89 (mydiv, myspan) var elsArray = document.getElements(".myclass[rel=89]"); // get an array of elements that are myclass and rel is not 89 (mydiv2) var elsArray = document.getElements(".myclass[rel!=89]"); // get the first element that has class myclass and rel=89 (mydiv) var elObject = document.getElement(".myclass[rel=89]"); // get an array of null links (to anchors) - (null links #0,1,2) var links = document.getElements("a[href=#]"); // all links within the mydiv2 layer only var localLinksArray = $("mydiv2").getElements("a"); // get all required fields (surname, message) var requiredFields = document.getElements("input.required textarea.required");
The examples for selectors are potentially endless as are the possiblities for use. There is nothing to prevent you from using the old document.getElementById() function, or even document.getElementsByTagName(). There is even a new function coming out now to a browser near you (perhaps) – getElementsByClassName(). But that’s just the point – by using a framework, you are guaranteed compatibility NOW and with future releases. If a new browser ‘Steel’ comes on the market that provides access to its DOM elements by way of a function document.ById(), you would not have to go and update every single bit of javascript that on your sites to provide support for it – all you’d do is update your framework and grab a coffee – the major frameworks will always pickup on browser changes and new versions. In fact, I expect most are readying updates to cover the new Google Chrome browser and webkit changes.
Compatibility and performance
Different browsers and different versions have always had their old ideas about what’s the best way to ‘do things’. One can’t help but apploud the peioneering spirit of the Internet Explorer engineers, who pretty much just made stuff up as they went along and ignored many a WC3 standard in the process… The thing that frameworks give you that you will learn to appreciate the most is a bridge between all the browsers. You no longer need to worry if IE6 will fire an onload event when other browsers fire oncomplete. You also won’t have to worry about mistakes in misfiring of onmouseout events when hovering over child elements (IE bug, of course). Frameworks do the worrying for you and fix those common errors that are deemed fixable.
As for performance, it really, really can’t get much better than relying on a bunch of crazed javascript coders and programmers, many of whom are involved in the development of Mozilla, to write, refactor and improve all your functions for you! You get what you want from the DOM, in the fastest possible way. Yes, I am talking ‘selectors’ again and there are lots of test suites / javascript framework benchmarking results of all the major frameworks. More or that will come in part 2 – for now, suffice to say: doing a for() loop through your elements just won’t cut it.
AJAX out of the box
Enough selecting, it’s time to use some keywords that spell ‘magic’ to any marketing pro out there: ajax. web 2.0. ooooh….
Most of today’s modern frameworks will have a way of dealing with XHR requests, more commonly referred to as AJAX. Whereas it does not take much to get going with a simple AJAX request, frameworks have it polished into perfection. You can easily set things like:
- method (GET / POST)
- target url
- setting up events (start, sucess, failure)
- parameters to url as GET or POST data
- displaying desponse into a layer/table element
- evaluating response as javascript in a safe way
- processing response AND evaluating <script> tags
Say, you have an element with some summary text and you’d like to attach a click event to it to show the full article text. Here is how that AJAX request can look in mootools:
$("mydiv").addEvent("click", function() { // make a click on mydiv2 to callup an ajax function that gets // the full contents of the layer replaced and runs through some scripts new Request({ url: "/index.php", method: "get", evalResponse: false, evalScripts: true, update: $("mydiv"), // replaces the text there at the moment onComplete: function() { // already updated to full text, no need for the event to remain $("mydiv").removeEvents(); } }).send("action=getFullText&id="+this.get("rel")); });
Same functionality (just the AJAX call) in jQuery would go like so:
$.ajax({ url: "index.php", cache: false, success: function(response){ $("#mydiv").append(response); } });
In part 2, we will review how to code a few practical snippets that can build you a core library for your site – things like, tooltips, bubbles, form checkers, expanding and collapsing menus and more. And of course, my advice on choosing the right framework for you (always a subject of debate and controversy)
Round-up of 10 promising new javascript frameworks by Six Revisions, click here.
yeah, read that on ajaxian a while back. Interestingly enough, according to http://ajaxpatterns.org/Frameworks, there are a lot more than 250 frameworks in existence now… not sure why anyone would waste time and resources writing something from scratch when others have done it before them, for free and probably better =>
[…] and methods you can use in your own pages. I tend to use mootools but anything will do – read my post on selecting a framework. In this example, we WILL use mootools, […]
[…] may be difficult to believe but there are people out there that have yet to realise the benefits of using mootools. Recently, I tried to help out on the Digital Point javascript forums on the subject of image […]
[…] a website developer it is a matter of choice whether you want Angularjs, backbonejs or Reactjs for a JavaScript framework. Maybe this will be helpful if you find it difficult to decide which framework gives you the better […]