dans.blog


The miscellaneous ramblings and thoughts of Dan G. Switzer, II

jQuery Calculation Plug-in v0.3 released...

I've updated the jQuery Calculation Plug-in with a few changes:

  • Refactored the aggregate methods (since they all use the same core logic) to use the $.extend() method
  • Added support for negative numbers in the regex (now uses /-?\d+(,\d{3})*(\.\d{1,})?/g)
  • Added min/max aggregate methods
  • Added defaults.onParseError and defaults.onParseClear methods to add logic for parsing errors

The onParseError/onParseClear methods are useful when you need to flag the element that threw the error—such as changing the background color of the element to highlight it doesn't contain a valid number.

Make sure to check out the example of the avg() method on the documentation page. If you input an alpha string into any of the fields, the field will turn red to indicate the parsing engine could not find a number in the field.

I also added support for negative numbers—which was an oversight on my part.


jQuery Tip: Matching Paired Elements

A common task you might want to accomplish in jQuery is to match elements that are paired together. For example, you have a page full of authors and only want to show their biographies if they click on a link.

Your first thought might be to do something like the following:

$(document).ready(function (){
    $("dt").click(function (){
        $("dd").slideDown();
    });
});

The problem with this approach is that when you click on the <dt /> tag it will open all of the <dd /> tags. This is because the selector being used specifies all of the <dd /> tags and doesn't do anything to filter the tags to the specific matching tag.

more…


Updates to jQuery Field & Calculations Plug-ins

Over the weekend I made a few changes to my Field & Calculations plug-ins. One big change is I moved the plug-ins to the jQuery SVN repository. This should help people to find the plug-ins and will provide an easy way to stay on top of the changes.

The biggest overall change to the Field Plug-in is the addition of callbacks to the a few of the methods, especially the createCheckboxRange. This allows you to do something like change the background color of the checkbox's row. I also added a default setting (checkboxRangeKeyBinding) which allows you to configure which keyboard event triggers the range selection. This still defaults to the [SHIFT] key, but I can see where you might want to change this binding in certain situations.

The changes I made to the Calculation Plug-in should make it even easier to implement. I altered the sum() and avg() methods so that you can now create bindings to easily update the page. Previously, the methods only performed the calculations, so you had to write your own binding calls. Now if you want to update the element #totalSum whenever the user changes a value in a field beginning with the keyword "sum", you can do: $("input[@name^=sum]").sum("keyup", "#totalSum");

Here's a list of the changes that I've made in the past few days:

Field Plug-in

  • Moved source code to jQuery SVN repository: http://jqueryjs.googlecode.com/svn/trunk/plugins/field/
  • Changed the limitSelection() function to use an options argument, instead of all the individual arguments
  • Optimized the createCheckboxRange to reduced complexity and code size. Functionality has not changed.
  • createCheckboxRange() no longer breaks the chain
  • Added callback to autoAdvance() method
  • Added callback to createCheckboxRange() method
  • Added configurable setting for the [SHIFT] key bind to the createCheckboxRange()
  • Added the $.Field.setProperty() and getProperty() methods
  • Fixed "bug in checkbox range" (http://plugins.jquery.com/node/1642)
  • Fixed "Bug when setting value on a select element and the select is empty" (http://plugins.jquery.com/node/1281)

Calculation Plug-in

  • Moved source code to jQuery SVN repository: http://jqueryjs.googlecode.com/svn/trunk/plugins/calculation/
  • Fixed bug in sMethod in calc() (was using getValue, should have been setValue)
  • Added arguments for sum() to allow auto-binding with callbacks
  • Added arguments for avg() to allow auto-binding with callbacks


Watch jQuery Calculation Plug-in in action!

A few weeks ago I posted a blog entry on my jQuery Calculation Plug-in. However, I never think I do an adequate job of describing what it does so I thought a little video might be more useful. Since I just installed Jing a few days ago, I thought this plug-in made a perfect candidate for my first Jing post!

Something I forgot to specifically mention in my demo, but which I think is really significant, is that the dynamic calculation code would work regardless of how many rows were in your table. If you only had 1 item in your basket or 20 items, the exact same code is used. The key is to use a naming convention that is consistent and easy for jQuery to parse.

My original post goes into the technical details behind the demo above, so make sure to read the post for the detailed information on what's going on.


jQuery fadeToggle() plug-in

Karl Swedberg posted this 3 line nugget to the jQuery mailing list this morning and I thought it was worth of blogging. It uses a technique I was previously unaware and that's the animate() method allows for toggling of opacity. This might be a commonly known feature, but I rarely use the animate() method directly—which is probably why I wasn't aware of the feature.

Anyway, here's Karl's code:

jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback);
};

This creates a simple jQuery plug-in that you can now use like:

// attach the onclick event to each anchor tag with a class of "div-toggle"
$("a.div-toggle").click(function () {
    // fade-in/out the element with the id of "my-div"
    $("#my-div").fadeToggle();
    // return false to prevent the anchor tag from following the href rule
    return false;
});

You can also pass in arguments to control the speed, easing effect or the callback to run after the fading is complete. If you want to use the callback argument without using the speed or easing arguments, just pass those arguments a value of null.


jQuery Calculation Plug-in: Making calculating easy...

I actually wrote this plug-in months ago, but only made passing mention about in on the jQuery mailing list. Since the topic of dynamic calculation came up again today on the mailing list, I thought I'd go ahead and officially announce the plug-in here.

My jQuery Calculation Plug-in was designed as a generic mathematical library to make it easy to do things like sum or average values that are displayed on the page. For example, to get the sum of all of the elements with the class of "price" you'd use:

alert( $(".price").sum() );

more…


Aptana releases Ajax Server "Jaxer"

Aptana just released a new project called Jaxer. In a nutshell, Jaxer is server filter which parses files and can execute JavaScript on the server. It's like a headless version of Firefox. All your client side libraries (like jQuery) will run in Jaxer—which is pretty neat.

What this means is that the JavaScript you write can be used in both the client and the server. Jaxer actually resolves one of the most complicated problems web developers face—ensuring data is validated using the exact same rules on both the client and the server. Because Jaxer is able to execute your JS code on the server, you can write one set of validation functions and use them both place.

Aptana's posted a screencast showing a simple client/server validation example using Jaxer that I recommend viewing. It's a simple example, but shows off the potential power of Jaxer.

I also recommend checking out Ajaxian's post on Jaxer as well as John Resig's post which both provide example code and give further insight.

At this point this product has a high "Cool!" and "Wow!" factor, but I really wonder who their target audience is. Hopefully I'll have some free time to play around with this sometime soon.


jQuery celebrates 2nd Birthday with v1.2.2 release!

jQuery turned 2 years old today. To celebrate turning two, John Resig and gang released jQuery v1.2.2. Some of the key changes are:

  • 300% Speed Improvements to $(DOMElement)
  • $.ready() Overhaul — this is supposedly fix several bugs and provide even more consistent behavior across platforms. (NOTE: For those unfamiliar with the $.ready() function, it's designed to replace the window.onload event and fire immediately after the DOM is ready and not wait for all images to finish loading.)
  • New .bind(”mouseenter”) / .bind(”mouseleave”) events — these events are improvements on the typical mouseover/mouseout events as they don't fire when entering children elements (which is generally not the desired behavior.)
  • New .bind(”mousewheel”) event — this new event allows you to bind events to the mouse wheel.
  • The :not() selector now supports complex expressions
  • New AJAX "Accept Headers" added to XHR requests
  • Over 120 bug fixes
  • Test suite now includes over 1157 unit tests


Ajax Rain mentions jQuery Field Plug-in!

Ajax Rain blogged about my jQuery Field Plug-in. If you like my jQuery Field Plug-in (official site) make sure to go vote for it on Ajax Rain!


jQuery: Understanding the "chain"

Yesterday I was writing some jQuery code and I thought I came across a bug—until I realized it was a bug in my way of thinking and not with jQuery.

What I was trying to do is to dynamically append to the body tag some html that looked like this:

<div>
    outer
    <div>
        inner
    </div>
</div>

more…


Expiring Session via AJAX using HTTP Response Headers

Raymond Camden recently asked on his blog How can you timeout a session in an Ajax-based application?. Most of the comments on the entry relate to doing some kind of server-ping, but my suggestion would be to just let your application tell your Ajax code when the session actually expires.

The concept is to use HTTP response headers to inform your Ajax request when the session has actually expired. This allows you to do everything in one single call, without having to worry writing other code. Besides you should be adding some failure code to your Ajax calls anyway, so this fits right in with good Ajax practices.

There are two basic approaches you can take. Using a "custom" response header or sending back HTTP status code to indicate the user is no longer authorized to view content.

more…


ySlow? Well find out with Yahoo!'s new Firebug plug-in...

Yahoo! has just released a new Firebug plug-in called ySlow. I just finished installing it and playing around with it for a few minutes and it definitely looks like it could be one of those must have web developer tools. It provides the following:

  • Performance report card
  • HTTP/HTML summary
  • List of components in the page
  • Tools including JSLint

The Performance Report card is pretty slick. It provides lots of tips on improving performance—such as ways to minimize HTTP requests, removing duplicate tags, adding expiration headers, etc.

more…


IE6 & IE7 quirks with cloneNode() and form elements

I've been working on some code for a contracting client which involves a really cool drag-n-drop interface for building forms on-the-fly. While working on the project, I ran into an issue in IE6 when dragging a <div /> element that form fields and there values had been changed by the user, the values were not properly reflected when I'd copy the node using the cloneNode() DOM method.

It turns out IE 6/7 doesn't properly clone some form elements when you use the cloneNode(true) and the form element is a checkbox, radio or select element. My suspicion is this is because MSIE stores the element in a non-XHTML way (if you do an innerHTML on the source element you'll see that checkbox elements have a "CHECKED" attribute with no value.)

I was able to work around the issue by doing the following:

more…


jQuery version of Tetris

I've been meaning to blogged about this for a couple of weeks and just haven't gotten around to it, so I thought I'd do it now so I can get rid of the e-mail in my inbox. :)

Here's a pretty cool jQuery implementation of Tetris. Pretty neat to seem something totally recreational done with jQuery. I've been thinking about just trying to put together some small, cool, mostly useless examples using jQuery just to show off some of the things you can do with a 19k JavaScript library. :)


jQuery Updates...

A couple of cool tidbits on the jQuery front.

Remy Sharp has written a nice, clear, concise entry on demystifying jQuery's this object. He does a really good job explaining the differences in what this means depending on the context of what you're doing. This, no pun intended, is one of the things that can be a little confusing when you're new to jQuery since the this keyword can either be a pointer to the current DOM element or a jQuery object—depending on the context of your code. Remy's write up should help to clear this up for any new jQuery users.

Ralf S. Engelschall has a released jQuery Plug-in for cross-site AJAX. His plug-in allows you to communicate to a 3rd party domain in a similar manor to the $.getScript() call. The new function he introduced is called $.getScriptXS(). He's even added support for callbacks, so you'll know when the script has loaded. Very nice!

more…