For the past eight(8) years Schalk Neethling has been working as a freelance developer under the pseudo of Volume4 and is now the president of Overt Strategy Consulting. During this period he has completed over 300 projects ranging from full web application development to complete branding. As president and lead developer of Overt Strategy Consulting, Schalk Neethling and his team has released a 100% Java standards based content management system called AlliedBridge and business document exchange and review system, called Doc-Central. Schalk Neethling is also actively involved on a daily basis in the open source, web standards and accessibility areas and is a current active member of the Web Standards Group. Schalk is also the co-founder and president of the non-profit The South Web Standards and Accessibility Group, which aims to actively educate and raise awareness of web standards and accessibility to both the developer society as well as business large and small. Schalk also has a long relationship with DZone and is currently zone leader for both the web builder, css.dzone.com, as well as the .NET zone, dotnet.dzone.com, and you can find a lot of his writing there as well as on his blog located at schalkneethling.alliedbridge.com. Schalk is constantly expanding on his knowledge of various aspects of technology and loves to stay in touch with the latest happenings. For Schalk web development and the internet is not just a job, it is a love, a passion and a life style. Schalk has posted 173 posts at DZone. View Full User Profile

Making Element Selection and AJAX simple with DOMAssistant

05.13.2008
| 12731 views |
  • submit to reddit

With this article, my goal is to show you how easy it is to implement basic element selection and then add some nice dynamic retrieval of content through AJAX by using DOMAssistant.

Author: Robert Nyman

A little background

The idea behind DOMAssistant is to provide a lightweight JavaScript library, to help you out with your everyday scripting tasks. One of its strongest parts is having the fastest and most consistently accurate CSS selectors out there, which is the common starting ground for almost every scripting task there is in today's modern world of element referencing.

Just like the Safari web browser and its continuous gained success, we believe that there is a great interest for having something perform as fast as possible, and having a small yet rock solid and easy-to-use features. For those needing to extend on that, DOMAssistant has a very powerful yet simple plugin mechanism to add the specific functionality you need.

A demo page

I've set up an example page, with a very basic HTML structure to showcase the functions described below. Let's start by looking at the HTML within the body element:

<div id="container">
<h1>DOMAssistant Demo Page</h1>

<p>
There will be three alternatives below, and each
will make an AJAX call to dynamically add
content to the page.</p>
<ul>
<li>
<a id="html-link" href="content-through-html.html">
Content through HTML
</a>

</li>
<li>
<a id="json-link" href="content-through-json.js">
Content through JSON
</a>
</li>
<li>

<a id="xml-link" href="content-through-xml.xml">
Content through XML
</a>
</li>
</ul>
<h2>Content presentation</h2>

<p id="content-presentation">
The content retrieved will be presented here.
</p>
</div>

DOMAssistant.DOMReady

First, the major initializing function is called when the DOM is loaded; as opposed to the window when with all its external references has to have finished loading. The syntax for this in DOMAssistant is with the DOMAssistant.DOMReady method:

DOMAssistant.DOMReady(function/functionRef/functionNameAsString)

Examples are:


DOMAssistant.DOMReady(function () {
alert("Hello, my friends!");
});

function sayWelcome () {
alert("Welcome!");
}
DOMAssistant.DOMReady(sayWelcome);

DOMAssistant.DOMReady("sayWelcome()");

Selecting elements

Looking at most JavaScript libraries in the market, they're based on using CSS selectors to find and work with one or several elements in a web page. Basically, CSS selectors are offering you the exact same possibility with JavaScript as you have in CSS to refer to elements.

And, actually, the CSS selectors offered by DOMAssistant and other JavaScript libraries, are giving you even more options since they completely support CSS 1 - 3; something which isn't currently available in any web browser. All the CSS selector combinations are available in the CSS selector page.

In the demo page, I've used a number of CSS selectors to give you a glimpse of how versatile such an approach can be:

Example selections

// Selects an element with the id "html-link"
$("#html-link");

/* Selects the link that is the child of an
LI element, which in turn is the
second child of its parent
*/
$("#container ul li:nth-child(2) a");

/* Selects the link that is the child of an
LI element, which in turn is the
last child of its parent
*/
$("#container li:last-child() a");

Adding events

Events are added to the links by using the addEvent method. The fist parameter is a string representing the event, e.g. "click", and the second is a function or function reference for how to handle the event.

To prevent the default behavior of the links to navigating to a new page, return false is used at the end of the event handling functions. You can also use DOMAssistant.preventDefault(evt) and/or DOMAssistant.cancelBubble(evt) to determine how an event's default action(s) should be handled.

Getting content with AJAX

There are four basic methods to get AJAX content with DOMAssistant:

Within the demo page, I cover all but post (which is material and grounds for another article covering form submission and similar things through AJAX).

The load method

The load method is the most straight-forward one. It takes two parameters: the first being a URL from where to get the content, and a second optional parameter stating whether the dynamically retrieved content should be added to the existing content or replace it. If omitted, the content is replaced.

$("#html-link").addEvent("click", function (evt) {
$("#content-presentation").load(this.getAttribute("href"));
return false;
});

What happens in the above code is that the link with the id "html-link", when clicked, will trigger a call to the load method of an element named "content-presentation", with the link's href attribute as the URL to get content from. Once the content has being returned, it will put that into the "content-presentation" element, by altering that element's innerHTML property.

The get method

The get method behaves about the same as the load method, but it doesn't automatically load that content into any element. Instead, the returned value comes as a reference for you to do anything you would like to present it.

$("#container ul li:nth-child(2) a").addEvent("click", function (evt) {
$("#content-presentation").get(this.getAttribute("href"),
function (response) {
var json = eval("(" + response + ")");
$("#content-presentation").replaceContent(json.content.text);
});
return false;
});

 

In this example, the returned value is in the JSON format. It is then turned into a valid JSON object, and then the json.content.text property value is extracted and presented into the page, in the "content-presentation" element.

The ajax method

The ajax method offers some more advanced functionality, such as manually specifying method, parameters, headers, response type etc. In this example, it is used to ask for content in the XML format:

function xmlResponse(xml) {
var content = xml.getElementsByTagName("text")[0].firstChild.nodeValue;
$("#content-presentation").replaceContent(content);
}

$("#container li:last-child() a").addEvent("click", function (evt) {
$("#content-presentation").ajax({
url: this.getAttribute("href"),
method : "GET",
callback : xmlResponse,
responseType : "xml"
});
return false;
});

This was just the beginning

I have just scraped the surface with what you can do with DOMAssistant, and how extremely simple it is to retrieve content and load it dynamically into a web page. If this seems interesting, please try it out! If you have any questions or stumble upon a problem, just let us know in the DOMAssistant discussion group.
Published at DZone with permission of its author, Schalk Neethling.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)