Yelotofu

Yelotofu ~ “In building standards compliant sites we are creating a better Web for the future.”

Tip: getting values from an options list

So, if you've ever converted an options list into a single array of values you might have intuitively done this:

var select = $('#mySelectElement')[0];
var values = new Array();
for (var i=0; i < select.length; i++) {
  values.push(select.options[i].value);
}

Pretty boring aye?

There is a snazzier (is that a word?) alternative, which is to use jQuery.map:

var select = $('#mySelectElement')[0];
var values = $.map(select.options, function(n) {
    return n.value;
});

OK, only one line saving but doesn't that feel good?!?

Labs: UI inlineEdit

After my last tutorial on building a simple inlineEdit plugin I converted the concepts into a UI widget. It's now sitting in labs for you to use, pick apart and devour:

http://jquery-ui.googlecode.com/svn/branches/labs/inlineedit/demo.html

If you inspect the source code you will notice the structure is quite different. It's actually pretty much the same functionality wise but I have separated each piece into smaller chunks. This makes it easier to extend in future (I plan to write more on ways to extend UI widgets in another post).

Here's a quick peek at the features:

  • Basic inline editing - click, edit, save
  • Ability to save on pressing ENTER key
  • Cancel by un-focussing the input or clicking cancel
  • ThemeRoller ready
  • Customisable empty placeholder
  • Save and Cancel callbacks
  • Cancelable Save callback (so you could script a cancel action)

As usual please feedback and help improve this widget either by commenting here or on the InlineEdit design & planning page

Enjoy!

jQuery Inline Edit tutorial

A friend recently asked me to review his edit-in-place code which turned out to be a modification of the one found at http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax. Reading the tutorial on that page I asked myself how I would do this differently? Defining a global setClickable() function and then calling $('#editInPlace").click() is totally uncool, essentially limiting yourself to one edit-in-place area per page.

Since the concept of edit-in-place is so simple and the implementation should be likewise I want to try and tackle this as a tutorial by going through concepts and teaching to build from scratch.

The concept

There's a piece of text on a page, e.g. a heading or paragraph, looking plain and un-interesting. When you hover over it however a visual highlight, usually pale yellow, indicates that it's something special - an editable region. You then click on the text and it magically transforms into an editable box with save and cancel buttons tagged at the end. On clicking either save or cancel the editable box transforms back into its original form with text updated if saved.

The build

What we want to do is put these concepts into code whilst building something that's re-usable. A plugin will do the trick! Let's call our plugin inlineEdit.

We are only 3 steps away from achieving our goal! Follow along...

Step 1: Getting the basics right

The basic functionality consists of a static text element (span, div etc...) that can transforms into an input element on click. And on hover the text element will highlight to indicate special interactions.

Here's our first pass: Basic Interaction

Code explanation: Our plugin accepts a CSS class name defined in a stylesheet which is used to toggle the text element's classname - a class defining a background-color typically #ffC is sufficient for this. On clicking we replace the entire contents of the original text element with an input element and pass the original content into the input as its value. For now changes are saved when the input loses focus.

Step 2: Save, Cancel & Callbacks

As you may notice above we saved on blur and there is no way of canceling changes. Let's improve the interaction by adding a save button. This is important as you'd want to do something with the changes or allow a user to manually cancel. Every application does something different at the saving stage so we'll simply define a save callback and let the implementer decide what to do on save, be it Ajax post or what not. The save action is also cancelable by returning false inside the callback.

Here is our second pass: Save, cancel and callbacks

Step 3: Finishing Off

Our plugin is nearly there. Just a few nice finishing touches remaining. We want to give the user ability to change the button label and pass an initial value. Also to make the plugin more re-usable we want to move the core plugin code out to a separate file and reference it instead. To set the stage for further improvements in the future we also split the code into two distinct clauses.

Final result: Live Demo and source code is here

Usage

Now to use this brand spanking new plugin we simply apply it to any DOM element like so:

HTML

<span class="editable">Hello World!</span>

JavaScript - Basic

$(function() {
  $('.editable').inlineEdit();
});

JavaScript - Customised button label with save callback

$(function() {
  $('.editable').inlineEdit({
    buttonText: 'Add',
    save: function(e, data) {
      return confirm('Change name to '+ data.value +'?');
    }
  });
});

Feedback welcome - if you happen to improve upon this code base please share-a-like!

Enjoy!

Update 26-Aug-09: Added placeholder for cases when text is empty; changed label option to buttonText to minimise confusion.

Update 18-Oct-09 Fixed bug in setting initial value via script.

Update 17-Jan-10 Moved code to http://github.com/caphun/jquery.inlineedit. I will continue to improve this plugin from there. Feel free to fork it!

jQuery.com website redesign

The long overdue redesign of jQuery.com has finally landed! I like the new design as it's more intuitive and inline with jQuery UI's design. This redesign will certainly help pitch jQuery to new comers; for many the decision to go with another framework has purely been based on the ugliness of the old jQuery website, that should hopefully change now.

Old:
old jQuery.com design

New:
new jQuery.com design

However, I still see much room for improvement. The website clearly lacks that magical touch you could easily achieve with a sprinkle of FX and UI. The fade-in boxes on the homepage don't work for me and display erratically when you mouse over them quickly. Hopefully the jQuery team will change this soon.

That said, hats off to the team as they have done an excellent job, as always, in giving us this redesign and of course — jQuery. Thanks!

jQuery: Shuffle Plugin

I recently came across a really compact array shuffling function on JSFromHell.com, which I thought would make a nifty jQuery plugin.

This jQuery shuffle plugin could be applied to any HTML element or Array object.

 
(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
})(jQuery);
 

Due to line wrapping issues in this post I inserted a few hard carriage returns in the above snippet (sorry).

Example 1: shuffle an unordered list

 
$('ul').shuffle();
 

Example 2: shuffle an array

 
var arr = [1,2,3,4,5,6];
arr = $.shuffle(arr);
 

There is a demo here. And for those interested I encourage you to download the plugin for closer inspection.

JavaScript: Event Delegation

Recently, I've been hearing much about event delegation. Many new to this concept seem to be baffled by the term. However, it really is a simple idea when you realise what's involved.

Put simply, event delegation is the practice of directing events on parent DOM elements who then listen on their children for events.

To understand event delegation and why it works you should read this ppk article before continuing — JavaScript Event Order.

Back? OK, so now you know about event capturing and bubbling the concept is easier to comprehend.

Event delegation takes advantage of the fact that actions performed on a child element always bubbles up to the top. Traditionally events are handled on the element that fired it, for example (excuse my jQuery) :

$('button').click(function(e) {
  alert('You clicked on me?');
});

Now rather than handling the click event shown above on the element itself we could delegate it to a parent because we know all events eventually bubble to the top, so

$('html').click(function(e) {
  if ( $(e.target).is('button') )
    alert('You clicked on me?');
});

produces the same result as the first code snippet.

Did you notice e.target? This is the essence of event delegation. As the event bubbles it keeps a mental note of its starting position in its pocket; e.target is a reference to the first element the event started bubbling from. In the above code sample that would be button.

That's event delegation in a nutshell!

Now, you might be asking - why should I use this rather than traditional one-to-one event handling?

Here are a few reasons:

  • In event delegation you bind one event handler to handle events on multiple elements. In traditional event handling you have to create a thousand event handlers to handle a thousand events. As you would expect event delegation is less resource expensive and could result in quicker response times
  • If Ajax or DOM manipulation happens, re-binding event handlers usually follow. Event delegation avoids re-binding by listening to a parent you know won't be manipulated, i.e. html, body or the website container.
  • Event delegation makes for cleaner code if you have a large webapp demanding lots of event handling.
  • No need to worry about event order and bubbling issues as we're now taking advantage of this effect

In conclusion. Event delegation is not a replacement for Event handling - both have their uses depending on situation. Event delegation requires more planning and could be harder to debug due to the inherent abstractions. You just can't beat the humble event handler if all you want is a link opening in a new browser window. That said, you'd be mad not to use it if you have a complex app with thousands of event objects doing various operations from submitting a form to loading Ajax content.

Further reading:

jQuery UI Spinner

After contributing jQuery Numeric Stepper to the jQuery UI community. Paul Bakaus kindly asked whether I'd like to merge it with the official jQuery UI Spinner, of which I was more than happy to do out of pure love for jQuery.

The jQuery UI Spinner widget will be available with the soon to be released jQuery UI v1.6.

Here's a demo of the current incarnation.

Also, check out Subversion if you're interested in getting the latest and greatest.

Update: this spin control is currently in re-design phase and will come under intense refactoring to be leaner and meaner. So the UI team have decided to push back its release to v1.next, which means it will not be part of the final 1.6 release. Sorry guys!

Update2: I've posted an update on this here.

jQuery Numeric Stepper

As an experiement I ported over my Accessible Numeric Stepper into a jQuery widget and added some accessibility enhancements and new features in the process.

This widget utilises ui.core.js - a factory method object for creating widget classes. Widgets in jQuery are essentially plugins at heart but built to follow stricter coding standards in order to unify the underlying quality between developers. It also adds convenient mouse interaction classes and option settings among other things.

The result is jQuery Numeric Stepper an unofficial jQuery UI widget. Features include:

  • min, max, start and step size settings
  • supports decimal values and decimal step sizes
  • supports currency values
  • keyboard and mousewheel interaction - increment/decrement values via cursor keys, +/- keys and mousewheel

Download latest source code here

Bugs? Missing feature? Code improvements? Let me know!

Update: Features seen here are now part of the official jQuery UI Spinner, set for the 1.6 release of jQuery UI. More details.

Loving jQuery

In recent weeks I have come to love jQuery. jQuery is this lightweight, elegant and so-much-fun-to-code-with JavaScript library. You may already have it in your source code if you're using either the latest version of WordPress or Drupal.

jQuery is so easy to get to grips with, the documentation is simple to follow and complete with loads of code samples.

jQuery's elegance comes in the form of its ability to select DOM nodes through CSS-like syntax (i.e., CSS queries) in a compact way—brilliant for those who are already very familiar with CSS!

Most or even all actions start with a CSS query, which in a sense promotes the use of unobtrusive JavaScript as it's simply easier to use the $() syntax than add a function directly into HTML.

jQuery is also very much down to earth in a practical way providing a few neat toggle functions:

  • toggle — show/hide selected elements
  • slideToggle — show/hide selected elements with slide Up/Down effects
  • toggleClass — add/remove a class from selected elements

There are also some handy plugins such as the Flash plugin and the ifixpng plugin, which fixes PNG transparency for img elements and CSS backgrounds in IE.5 and IE6.

If something isn't built-in, extending jQuery is ridiculously easy via custom plugins. Here's one way you could define a custom plugin:

 
jQuery.fn.myPlugin = function() {
    // Your plugin code goes in here
}

To take advantage of jQuery's chainability you need only add a single line returning the current context object—this:

 
jQuery.fn.myPlugin = function() {
    // Your plugin code goes in here
    return this;
}

To demonstrate how easy jQuery is to extend I created a simple one line plugin to toggle fadeIn and fadeOut effects, see below.

jQuery fadeToggle plugin:

jQuery.fn.fadeToggle = function(s, fn){
    return (this.is(":visible"))
        ? this.fadeOut(s, fn)
        : this.fadeIn(s, fn);
};

Example usage:

jQuery(function($){
    $(".toggler").click(function(){
        $(".content").fadeToggle();
    });
});

A demo of jQuery fadeToggle plugin in action

High Performance Ajax Applications

Julien Lecomte, author of the YUI Compressor gave a talk on High Performance Ajax Applications. He refers to some of the tricks we learnt from Steve Souders' research on the 14 rules for faster-loading web sites but also gives us more insight specifically on fine tuning JavaScript to perform up a gear. I hope you learn a few neat tricks from this video, I know I did. :)

[source: YUIBlog]

« Previous Entries