Skip to main content Skip to footer

jQuery and MVC–Part 1

This is the first in a four-part series on using the JavaScript library jQuery with the ASP.NET MVC framework.

Introduction

In the beginning there was static HTML and it was good. The World Wide Web was in its infancy and anyone with a computer, a text editor, an FTP program and a connection to the internet – more than likely dial-up – could create and publish web pages. But quickly these pages became boring, as they were after all, static, and web publishers began clamoring for something to make their pages zing.

Then along came a scripting language called JavaScript, and changed the way web pages and sites looked and acted, creating new ways to provide interactivity between the user and the web server. It was first released by Netscape as LiveScript in September 1995, and was renamed to JavaScript in December 1995 when it was included in the release of the Netscape browser.

As a programming language it is dynamic, weakly typed, prototype-based and supports closures and higher order functions. Not to be confused with the Java language it does have some similarities in its syntax with curly braces “{}” and semi-colons “;” and copies many names and naming conventions. However like Java, it does have a fairly steep learning curve. Because of this, JavaScript “scripts” started to become more and more popular on web development sites, allowing for easy copy and pasting. While this made JavaScript to quickly become one of the most popular languages for web development, in some circles it gained the reputation of being a “kiddie” language.

In 1999, Microsoft released the IXMLHTTPRequest interface as part of their Outlook Web Access for Microsoft Exchange Server. The Mozilla Foundation developed a wrapper to use this interface through a JavaScript object which was called XMLHttpRequest. In April, 2006 the World Wide Web Consortium published a working draft to “document a minimum set of interoperable features based on existing implementations, allowing Web developers to use these features without platform specific code”. The last revision to the specification was in November, 2009. (http://en.wikipedia.org/wiki/Xmlhttp)

With the advent of Ajax (Asynchronous JavaScript and XML) in 2005, JavaScript had begun to be looked on more favorably by the programming community, and as a more full-featured language.

The Pros and Cons

As with all languages there are many pros and cons, likes and dislikes, friends and foes. JavaScript is no different and some of the most common are:

Pros

Cons

Dynamic
Easy to develop with and debug with the appropriate tools
Similar, comfortable syntax to Java, C#, C

Browsers seem to have their own JavaScript engine
Can be difficult to have the same behaviors act the same across browsers

The Development Experience

You get into the learning curve, and spend all your waking hours writing the most unique and elegant piece of JavaScript code, and test it in your favorite browser. It works just how you planned, until you open your site in a different browser. Ugh, events are different, you can’t seem to get to the correct DOM element, nothing just seems to work between browsers, let alone platforms. You pour over your trusty JavaScript manuals, scour forums, Google on Bing for obscure error messages, and generally get frustrated. You just feel like giving up, so what do you do?

JavaScript Libraries to the rescue

JavaScript libraries are pre-written snippets of code and controls which usually form a much larger JavaScript Framework. These libraries allow for the easier development of JavaScript intensive applications, as the majority of them handle the problems of cross-browser, cross-platform issues. Numerous libraries are available including, but not limited to, Dojo, Echo, Ext, Google Web Toolkit, jQuery, MochiKit, MooTools, Prototype, qooxdoo, Rico, script.aculo.us, Spry, and Yahoo! UI Library.

While each library has it’s good and bad points, it’s pros and cons, the rest of this series will focus the jQuery library, found at www.jquery.com

jQuery

In January 2006 John Resig, released the first version of jQuery at BarCamp NYC, as a free, open source, dual-licensed (MIT and GNU) library. According to http://trends.builtwith.com, jQuery is the most popular JavaScript library; with 38.62% of web sites tested using some form of the code. Some of the main features of jQuery are:

  1. Its syntax makes it easier to navigate the DOM (Document Object Model)
  2. Easily handles and binds events to any DOM element
  3. Creates both simple and complex animations
  4. Has a complete suite of Ajax grooviness baked in
  5. Easy extensibility with plug-ins
  6. Unobtrusive
  7. Microsoft bundles jQuery with ASP.NET Web Applications and ASP.NET MVC

That’s right. Microsoft has jumped on the jQuery bandwagon, and gives it full support, even committing code back into source control. In fact, you can call Microsoft Support and get help with jQuery.

Syntax

The learning curve for getting up to speed with jQuery is not terribly steep. In only a short time you can easily grok the basics, and in a few hours, do some really nifty things with jQuery.

The jQuery syntax is easy to learn with all statements starting off with a “$”. One of the cool things about jQuery is since other libraries may use the $ as well, to prevent collisions, you can use the literal “jQuery” instead. For example:

$(“some element”); or jQuery(“some element”);

DOM elements are selected by either their ID, or a className that has been assigned to them.

$(“#myElement”); returns the only ID in the DOM, “myElement”
$(“div.myElement”); returns all div elements having a class assigned of “myElement”

jQuery makes it very easy to traverse through the children of each element as well.

$(“div.main ul li”); returns all li tags within the div tag with a class of “main”

Whereas

$(“div.main”).find(“li”); returns the same collection as above.

You can select specific elements in the collection with special selectors such as :odd, :even, :first, :last, :not(), etc.

$(“div.main”).find(“li:odd”);
returns all odd (zero-based) li tags inside the div with a class of “main”

$(“div.main”).find(“li:even”);
returns all even (zero-based) li tags inside the div with a class of “main”

$(“div.main”).find(“li:first”);
returns the first li tag

$(“div.main”).find(“li:last”);
returns the last li tag

$(“div.main”).find(“li:not(li.someDifferentClass)”);
returns all li tags that don’t have the “someDifferentClass” assigned to them

Unobtrusive JavaScript

How many times have we added our own “BLOCKED SCRIPTonclick(doSomething();)” code directly in our elements. It makes it difficult to maintain and debug, and rails against the philosophy of separation of concerns. jQuery helps us to get away from this by using selectors and assigning events to the elements we have found.

Additionally, unless you have written some really terrible jQuery/JavaScript, if there is an error in your jQuery syntax, jQuery will fail gracefully. This means there won’t be any pesky little JavaScript error icons in your browser or JavaScript console.

Events

It is very easy to assign an event (click, focus, blur, etc.) to any DOM element with jQuery, and there are two main methods to do this.

The first is to wait until the DOM is fully loaded, which is checked by the jQuery event, .ready(). This event is fired when the DOM is complete and has been loaded into the memory of the browser.

$(document).ready(function() {
$(“myElement”).click(function() { doSomething(); });
});

The second method is to attach a “live” event to the element with

$(“myElement”).live(“click”, function(){ doSomething(); });

The differences between these two methods are slight, but important. In the first example, we are assuming there will be an element called “myElement” in the DOM. This could be an element that is hard coded in the HTML, a button, text field, image, div or p tag. However, with jQuery’s dynamic DOM manipulation, it is possible that you would reference an element that has not been created yet.

The .live() event attaches the function you want to call to all matched elements in the selector, regardless of if they have or have not been created yet.

In the examples above, the “doSomething()” is referencing a separate JavaScript function. Another method is to replace the “doSomething()” with more jQuery functions.

$("ul.demo li:odd").each(function (index) {
var targ = this;
setTimeout(function () {
$(targ).addClass("liSelected");
}, index * 500);
});
}

jQuery functions can have standard JavaScript functions in them as well. Can you look at the code above and figure out what this event will do?

First, all of the odd li elements in the ul element with a className of “demo” are selected. Second, the jQuery .each() function loops through the collection, setting a brief timer. Third when the timer is hit, the li element has the class of “liSelected” assigned to it.

jQuery’s silent error handling will not show any indication of something going wrong, just since the element hasn’t been created it won’t be able to have the click event attached to it.

Chaining

Once an element has been found, a reference to the element is kept in memory. So, instead of the following:

$(“div.myElement”).hide();
$(“div.myElement”).html(“howdy”);
$(“div.myElement”).addClass(“red”);
$(“div.myElement”).fadeIn(“slow”);

You can chain the actions like so:

$(“div.myElement”).hide().html(“howdy”).addClass(“red”).fadeIn(“slow”);

This makes for much cleaner or succinct code writing and will help with memory as well.

Stuff you can do

As this series progresses, we will dive deeper into all the jQuery goodness. Here is a sampling:

  • Selectors – find elements in the DOM
  • Attributes – get/set attributes of found elements
  • Traversing – moving up/down elements in the DOM
  • Manipulation – get/set contents of found elements
  • CSS – get/set style attributes of found elements
  • Events – fire on click, hover, load, etc. of found elements
  • Effects – fadeIn/Out, slideIn/Out, hide/show
  • Ajax – full and complete Ajax capabilities
  • Utilities – inArray, isArray, makeArray, etc.

Benefits

In closing the benefits of using jQuery are incredibly apparent. It is a solid, standardized JavaScript library, which allows for fast development, and gracefully fails with no glaring errors or frozen pages. Because of its popularity, there are lots and lots of examples, and it is very easy to get ramped up and understand its simplicity.

Check back next week when we will dive deeper into jQuery, and how you can easily spiff up your sites. Take a look at the attached demos, and send me some comments and questions.

James

MESCIUS inc.

comments powered by Disqus