jQuery 1.1a Released

The jQuery 1.1a has been released today by the jQuery team! Its important to note that this is an alpha version before you go out and install it in a production environment, but the jQuery team asks that people give it a round of testing prior to the release this weekend.

The “Quick and Dirty” on v1.1:

  • Its selectors are 10-20x faster than those in jQuery 1.0.4.
  • The documentation has been completely revamped.
  • The complexity of the API has dropped by 47%.
  • It has a ton of bug fixes.
  • It has a bunch of great new features.
  • … and it’s still the small 19KB that you’ve come to expect.

With this release come a lot of API changes:

Firstly, :nth-child() now starts at 1, instead of 0.

A number of methods have been re-organized/re-named. Here’s the translation of old to new functions:

Old Way (1.0.x) New Way (1.1)
.ancestors() .parents()
.width() .css(”width”)
.height() .css(”height”)
.top() .css(”top”)
.left() .css(”left”)
.position() .css(”position”)
.float() .css(”float”)
.overflow() .css(”overflow”)
.color() .css(”color”)
.background() .css(”background”)
.id() .attr(”id”)
.title() .attr(”title”)
.name() .attr(”name”)
.href() .attr(”href”)
.src() .attr(”src”)
.rel() .attr(”rel”)
.oneblur(fn) .one(”blur”,fn)
.onefocus(fn) .one(”focus”,fn)
.oneload(fn) .one(”load”,fn)
.oneresize(fn) .one(”resize”,fn)
.onescroll(fn) .one(”scroll”,fn)
.oneunload(fn) .one(”unload”,fn)
.oneclick(fn) .one(”click”,fn)
.onedblclick(fn) .one(”dblclick”,fn)
.onemousedown(fn) .one(”mousedown”,fn)
.onemouseup(fn) .one(”mouseup”,fn)
.onemousemove(fn) .one(”mousemove”,fn)
.onemouseover(fn) .one(”mouseover”,fn)
.onemouseout(fn) .one(”mouseout”,fn)
.onechange(fn) .one(”change”,fn)
.onereset(fn) .one(”reset”,fn)
.oneselect(fn) .one(”select”,fn)
.onesubmit(fn) .one(”submit”,fn)
.onekeydown(fn) .one(”keydown”,fn)
.onekeypress(fn) .one(”keypress”,fn)
.onekeyup(fn) .one(”keyup”,fn)
.oneerror(fn) .one(”error”,fn)
.unblur(fn) .unbind(”blur”,fn)
.unfocus(fn) .unbind(”focus”,fn)
.unload(fn) .unbind(”load”,fn)
.unresize(fn) .unbind(”resize”,fn)
.unscroll(fn) .unbind(”scroll”,fn)
.ununload(fn) .unbind(”unload”,fn)
.unclick(fn) .unbind(”click”,fn)
.undblclick(fn) .unbind(”dblclick”,fn)
.unmousedown(fn) .unbind(”mousedown”,fn)
.unmouseup(fn) .unbind(”mouseup”,fn)
.unmousemove(fn) .unbind(”mousemove”,fn)
.unmouseover(fn) .unbind(”mouseover”,fn)
.unmouseout(fn) .unbind(”mouseout”,fn)
.unchange(fn) .unbind(”change”,fn)
.unreset(fn) .unbind(”reset”,fn)
.unselect(fn) .unbind(”select”,fn)
.unsubmit(fn) .unbind(”submit”,fn)
.unkeydown(fn) .unbind(”keydown”,fn)
.unkeypress(fn) .unbind(”keypress”,fn)
.unkeyup(fn) .unbind(”keyup”,fn)
.unerror(fn) .unbind(”error”,fn)

What’s more? Well, the jQuery team will be posting throughout the week on all the cool new things you can do with jQuery 1.1. I’m looking forward to seeing the changes! Oh, with regards to changes, its important to note with that list of functions above…the old method will no longer work come v1.1. To keep those functions in use, a ‘helper’ library will need to be used…chances are that won’t be available until the 1.1 final.

The Ajax Experience: jQuery Toolkit

jquery I went to The Ajax Experience with high expectations of catching some great tips regarding development in an Ajax environment. At the same time, I was sure of my previous decision with the use of Prototype and Script.aculo.us was as good as it gets (without diving into the widgetized world…e.g. Dojo). I attended John Resig‘s presentation on jQuery and I became a convert.

John’s presentation was less of a presentation and more of a Q&A Demonstration, which suited me fine. As soon as I knew where to download the code, I popped open my laptop and started fiddling around with the toolkit – passively paying attention to the questions and answers, as they tended to be extremely basic questions…you see, jQuery is pretty darn intuitive.

jQuery’s mantra is “Find stuff and do stuff to it”

Yeah, I wasn’t converted because jQuery was the first toolkit to support chaining and that it executes it nicely. Nor was I converted because of its extensive plugin library. Nope. My conversion was the effecient findability of elements within the DOM! This is what really makes jQuery ballsy. The toolkit was built with findability in mind using already established standards! jQuery fully supports CSS1, CSS2, CSS3, and basic XPath when hunting for elements. For example:

Lets start with something simple:
Say I wanted to find all elements within the page that had the class: bork and hide them, I’d do:

$('.bork').hide();

Alright, say I wanted to find all anchor tags with the target set to _blank and add the class whee to it:

$('a[@target=_blank]').addClass('whee');

Now, lets say I want to find all anchor tags with the target set to _blank and add the class whee to them AND append (opens in a new window) as a sibling to the link itself.

$('a[@target=_blank]').each(
  function(){
    $(this).addClass('whee');
    $(this).after('(Opens in a new window)');
  }
);

Now, if I knew I was going to use the above a whole lot all over hell’s half acre, I could create a jQuery plugin that can be chained! Here’s how I’d create that feature and allow for the passing of class name:

jQuery.fn.opensInNewWindow = function(classname){
	return this.each(
		function(){
                        $(this).addClass(classname);
                        $(this).after('(Opens in a new window)');
		}
	);
};

Now, when I want to put Opens in a new window on a series of elements, I can do so with my newly created plugin:

$('a[@target=_blank]').opensInNewWindow('whee');

//I can do this for ANY element I want even if it isn't a link
$('span.bork').opensInNewWindow('zomg');
$('div#w00t ul.nav').opensInNewWindow('roflcopter');

Now, to make use of the chainability, you can write the plugin more simply than what I did up above. You can do this: (thanks to malsup, a commenter on this article)

jQuery.fn.opensInNewWindow = function(classname){
	return this.each(
		function(){
      $(this).addClass(classname).after('(Opens in a new window)');
		}
	);
};

Cake walk. As your proficiency in finding objects within a page increases, your code will become shorter.

jQuery currently has a very active community and mailing list (averaging at about 90 posts per day) so if you have questions regarding the toolkit, you can become a member and ask away… In addition, there’s a jQuery blog where John posts comparison code showing the difference between jQuery and other available toolkits. (here’s a Zebra striping example)

If you are still on the hunt for a JavaScript toolkit for Ajax, DOM manipulation, etc or you find your toolkit of choice too clunky, give jQuery a shot. You’ll be pleased with the results.

Script.aculo.us 1.6.2 Released!

Mir.aculo.us has announced the release of Script.aculo.us v1.6.2! This is primarily a bug fix, which is always a good thing. Here’s the change log:

* Fix a problem in the drag and drop logic if an reverting/drag ending draggable was initialized for a new drag (for example by clicking repeatedly) for all cases where the default start/revert/end-effects are used, fixes #4706 [thx tecM0]
* Fix possible memory leaks with Draggables, fixes #3436 [thx aal]
* Throw nicer errors when requires script.aculo.us libraries are not loaded, fixes #5339
* Make slider handles work when not displayed initially by using CSS width/height, fixes #4011 [thx foysavas]
* Update sortable functional test with onUpdate counter
* Make more Element extensions unit tests work on Safari
* Add the assertMatch unit test assertion for asserts with RegExps [thx Ian Tyndall]
* Fix a problem with Effect.Move causing “jumping” elements because of very low float numbers in some situations
* Fix a missing semicolon in dragdrop.js, fixes #5569 [thx mackalicious]
* Fix a slight inaccuracy with Effect.Scale that could lead the scaling to be one pixel off
* Be more prototypish with Effect.Transitions.linear
* Make Effect.Scale recognize font sizes that use the pt unit, fixes #4136 [thx aljoscha]
* Fix IE hack in Effect.Opacity, fixes #5444 [thx nicholas]
* Fix IFRAME layout fix for IE and Autocompleter, fixes #5192 [thx tommy skaue]
* Fix only option in onEmptyHover, fiex #5348 [thx glenn nilsson]
* Fix Effect.BlindDown and SwitchOff handling of supplied callbacks, fixes #5089 [thx martinstrom]
* Fix a problem with field focus on Ajax.InPlaceEditor and loading external text, fixes #4988, #5244 [thx rob]
* Do not attempt to scroll if scrollspeed is 0/0, fixes #5035 [thx tomg]
* Fix a problem with Sortable Tree serialization, fixes #4939, #4688, #4767 [thx Sammi Williams]
* Fix an endless loop with sliders, fixes #3226, #4051, #4765 [thx jeff]
* Make autocompleter work with update DIVs that have scrollbars, fixes #4782 [thx Tommy Skaue]
* Corrected options parsing on switchoff effect, fixes #4710 [thx haldini]

Get the latest release over at Script.aculo.us!

Script.aculo.us v1.6 Released

Great news over at Mir.aculo.us. It appears as if version 1.6 of my favorite DOM manipulation library, Script.aculo.us has been released! Thankfully the new version of Script.aculo.us uses Prototype v1.5.

This is sexy because now I can revert to downloading both Prototype and Script.aculo.us right from the Script.aculo.us site. (Hooray for being lazy)

Here’s an excerpt from the original post:

script.aculo.us 1.6 marks the switch over to Prototype 1.5 (1.4 will no longer be supported), which has really great new features and has undergone some refactoring to take advantage of the Prototype 1.5 niceties.

Other new stuff includes window-scrolling while dragging, performance optimizations and various bug fixes.

They are urging people to test out 1.6. Get on it!

MasterWish – Practicing What I Preach

masterwish MasterWish, my labor of love (created with my friends Zach Tirrell and Jon Emmons) is my playground for Ajax and Web 2.0 experiments.

If you haven’t been acquainted with the site, its a wishlist site with a schlew of features. The high point is the ability to secure down lists and grant access to specific buddy groups. I’m pleased to say that we have gained a decent member base in the past 8 months and I am also happy to say that things are going to change around shortly!

MasterWish was built using SAJAX as the tool of choice for Ajax communication but as I’ve mentioned in the past, I am a Prototype convert. My knowledge of Ajax, JSON, and general application structure has been morphing so much in recent weeks that I have held off in completely revamping the wish list site.

Things are changing. I have begun the work to implement the following:

  • Creation of more “hackable” Web Service APIs using SOAP and REST
  • Representation of data using both XML and JSON
  • Ajax powered by Prototype
  • Sweet DOM manipulation powered by Script.aculo.us
  • Separation of Layout and Logic with event:Selectors
  • and of course, we’re already doing: Server-Side Templating for greater separation of Layout and Logic.

Sign up. Stay tuned. Get gifts.

Prototype Makes Javascript Painless

prototype.gifPrototype is an excellent tool but lacking in documentation, causing me to fumble around and *gasp* look at the source code. As any developer knows, when reviewing code there is a chance that you may miss something or ignore what doesn’t seem interesting. In doing so, you may miss some sweet features that you would otherwise use.

I did stumble upon some Prototype Cheat Sheets that have helped immensely in exposing functions that existed in Prototype that I had no clue were there. Desipte the exposure of function names, I was at a loss for what some of them did. Luckily, there is an article over at SergioPeriera.com that documents many of those functions! The documentation is fairly solid so I HIGHLY reccommend checking it out. Here’s one of the features of Prototype that I had seen the function but hadn’t a firm understanding on what it did:

Try.these()
Tries a number of functions in order. If the first fails, it attempts the second, and so on.

function getXmlNodeValue(xmlNode){
	return Try.these(
		function() {return xmlNode.text;},
		function() {return xmlNode.textContent;)
		);
}

Hugely cool. In addition, Ajaxian – which seems to be my source for many things Ajax – has pointed me towards this article over at SitePoint. I was aware of a number of the points mentioned in that SitePoint article, but a few stood out as super sexy. Here’s the juicy tidbits:

String.times([something])
Prototype adds a great method to Number, too. Say goodbye to your for loops!

// alerts "1", "2", "3" ... "50"
(50).times(function(n) { alert(n); });

Enumberable.each([something])
This does the same as a foreach in PHP. I’ve been looking for something like this!

// alerts "a is at 0" then "b is at 1" then "c is at 2"
["a", "b", "c"].each(function(item, index) {
 alert(item + " is at " + index);
});

Iterating over childNodes in the DOM
By default, even though nodes are represented in Array-like form, they do not have Enumerable available to them automatically. Here’s how to do it:

// add Enumerable to childNodes
var children = $A($("mydiv").childNodes);

// sets class="highlighted" for all child nodes of "mydiv"
children.each(function(child) {
 child.setAttribute("class", "highlighted");
});

Here’s one I found while digging around in the Prototype code that the article solidified my understanding:

Ajax.PeriodicalUpdater(id,file,options)
Periodically does an Ajax.Updater call!

new Ajax.PeriodicalUpdater("mydiv", "hello.php", {
 // initial number of seconds interval between calls
 frequency : 1,
 decay : 2
});

The decay option allows you to give your server a bit of a break if it’s returning a lot of identical responses. Essentially, every time PeriodicalUpdater makes a request, it compares the results with what the server returned last time. If the values are the same, it multiplies the interval by the decay value. So, for the above example, it would make the next request two seconds later, then four seconds later, and so on, until it received a different result from the server. At that point, the interval would be reset to one second.

Ajax.Responders.register(options)
Register global event handlers that are triggered for each and every AJAX request that happens on the page.

Ajax.Responders.register({
 onCreate : showLoader,
 onComplete : hideLoader
});

Node Manipulation in the DOM

DOM

I’ve been screwing around with DOM Manipulation for a few years now, doing stuff sporadically here and there. With my development of MasterWish and my recent interest in Script.aculo.us, I often find myself forgetting the various objects, functions and attributes relating to nodes. Hence the reason for this post. I want a quick and easy way to find the information…So, here’s a quick run-down of node structure:

Assuming we have the following simple structure:

<div id=”outer”>
    <div id=”inner_1″>
        Bork!
    </div>
    <div id=”inner_2″>
        OMG Lazerz Pew pew!1!!!1!
    </div>
    <div id=”inner_3″>
        <div id=”super_inner”>
            I like butter
        </div>
    </div>
</div>

We know the following (I completely understand the relationships between nodes…but I’m filling this out for completeness):

  • Node “outer”: is the parent of nodes inner_1, inner_2, and inner_3
  • Nodes inner_1, inner_2, and inner_3: are the child nodes of outer
  • Node inner_1: is the first child node of outer
  • Node inner_3: is the last child node of outer
  • Node inner_1: is the previous sibling node of inner_2
  • Node inner_3: is the next sibling node of inner_2
  • Node super_inner: is not a child node of outer, but is a child node of inner_3

Here are the node related functions available:

property description
nodeName name of the node
nodeValue value of node (only applicable to text nodes)
nodeType type of node – see below
parentNode parent, if one exists
childNodes list (array) of child nodes
firstChild first child
lastChild last child
previousSibling previous sibling
nextSibling next sibling
attributes list of attributes of an element
ownerDocument document containing the element

Here are the node types:

number description
1 an HTML element
2 an element attribute
3 text
8 an HTML comment
9 a document
10 a document type definition


Script.aculo.us Is My New Best Friend

Ajax is great. DOM manipulation is sexy. I’m fairly new to the Ajax world having only developed with with it since July. MasterWish was my guinea pig and continues to be my playground for all things Web 2.0. Luckily, my manager Ken is pumped up about this whole Web 2.0/Ajax thing which has allowed me to experiment with my projects at work as well and PSU should expect to see some sweet apps roll out over the next year!

Since July, I’ve been developing my Ajax applications and examples using SAJAX (Simple Ajax), a PHP/Javascript framework for Ajax development. It was great at first glance…a lot easier than building Asynchronous Javascript transactions from scratch. But despite its ease, it was a bit clunky. Last week I was stumbling around the web looking for anything new to suck up and found a beauty of a tool. Script.aculo.us.

Script.aculo.us is a Javascript Effects and Control framework developed by Thomas Fuchs, a software architect living in Vienna, Austria who, like me, was disappointed by current web application frameworks that made no sense to him. His framework is 3 things: Easy to Use, Simple, and Easy to Use. His libraries – built off of the Ajax framework, Prototype – blow SAJAX out of the water! Let me give you an example to, say, update a news title on an article (I won’t include the HTML markup as that is trivial):

Here’s what needs to be done to build a SAJAX call:

Step 1: Create a SAJAX Call Function

function x_updateTitle()
{
	sajax_do_call('/process_ajax.php',"x_updateTitle", x_updateTitle.arguments);
}

Step 2: Create a server side function to handle the update

< ?php
function x_updateTitle($news_id,$news_title)
{
	//do some database calls to update the title;
}
?>

Step 3: Edit the server side SAJAX file (process_ajax.php) and add x_updateTitle to the list of valid call functions

< ?php
include('sajax.php');
addFunctions('x_updateTitle');
handleClientRequest();
?>

Step 4: Call the SAJAX Javascript function from somewhere (in an onClick, onSubmit or something)

<a onClick="x_updateTitle(1, document.getElementById('news_title').value, 'callbackFunction');">asdfdf</a>

Here’s the equivalent in Script.aculo.us
Step 1: Create a server side function to handle the update

< ?php
function x_updateTitle($news_id,$news_title)
{
	//do some database calls to update the title;
}
?>

Step 2: Call the Script.aculo.us Javascript function from somewhere (in an onClick, onSubmit or something)

<a onClick="new Ajax.Request('/process_ajax.php', { asynchronous:true, parameters:'news_id=1&news_title=$(\'news_title\')', onSuccess:callbackFunction });">asdf</a>

Thats it! Its a big difference. Thats just the tip of the iceberg. Script.aculo.us has many features for implementing Drag and Drop with one line of Javascript code; fancy display/hide functions; dynamic DOM Element creation/deletion; field autocompletion; and various other visual effects. It slick. And to top it off, the Script.aculo.us website is pretty sweet! Luckily the documentation is excellent and is in wiki format. As Plymouth State moves into the Web 2.0 world, I’ll be pushing for Script.aculo.us/Prototype to be our Ajax standard. I have seen the light and it is good.