nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Category: jQuery

Posts relating to my favourite JavaScript library, jQuery.

Book Review: jQuery Enlightenment

About a month ago I had the pleasure of reading “jQuery Enlightenment” by Cody Lindley, a truly excellent book any Web Developer from beginner to advanced should have on their to-read list. Now I don’t usually enjoy reading books about code as they are usually as dull as dishwater; just something you have to get through before you can get onto the interesting part of making it work for you; jQuery Enlightenment is different.

It starts by going through the basic concepts behind jQuery and how to use it, if you are already a jQuery developer you could skip this, but as it’s packed full of short concise information you never know what you may learn. The book covers all aspects of jQuery you will need to get you started plus much more, from selecting, manipulating and traversing DOM elements all the way through to plug-ins and best practices.

There were countless times while reading I thought to myself “Well, I didn’t know you could do that!”, here’s one of my favorites:

1
2
3
4
5
6
7
8
jQuery(function($){
    $("#testanchor").bind("keypress mouseenter focus", function(e){
        //Event fires keypress, mouseenter and focus
        console.log(e.type);
        //Do stuff....
        return false;
    });
});

The bind() method can accept more than one event type, so the above function fires when any one of the listed events is detected on our #testanchor. I can’t remember the number of times where I’ve used multiple binds on the same element to achieve the same effect.

The book is packed full of useful code snippets like the one above that will save you time and effort when it comes to jQuery development. Being only 123 pages long it’s a fairly quick read, and it’s always great to have on hand as a reference when needed.

Grab it from here as an eBook for $15 or hard copies are available from lulu.com if you prefer that.

Mandelbrot Set Renderer using JavaScript and the Canvas API

A couple of weeks ago I happened to notice a tweet on Twitter by Christian Heilmann who linked to Geoff’s Mandelbrot Renderer. Geoff has created a tool that renders the Mandelbrot set using JavaScript and the Canvas API… amazing! I’ve been interested in fractals for a good few years but have never had the chance to look into generating them; so I decided to have a play with Geoff’s version and see what I could come up with.

The Mandelbrot set was named after Benoit Mandelbrot, who first saw the shape at IBM’s Thomas J. Watson Research Centre on March 1st 1980. It’s place is in a field of mathematics called complex dynamics, having not looked at any mathematics for a good few years it took me some time to get my head round exactly what was going on, and I still only have an inkling of what it all means.

Various forms found in the Mandelbrot Set

Here are just a few of the shapes I found using the tool. Why not try it yourself?

The image above – top left is arguably the most famous fractal; the three other shapes have been generated by zooming into the original fractal. The ‘image’ has infinite resolution, you can keep zooming in and it will always generate a new image. I’d say the only limitation is the browser / computer generating it.

One thing you will notice when zooming is the fact the Mandelbrot set is self-similar (or at least close to self-similar). At many points you will notice the original fractal shape, only on a smaller scale. This along with other repeating shapes creates a beautiful image purely generated by mathematics.

Note: Slight update to the render method here.

View a demo here. A few features I added:

  • Add render loader and restyled the form layout
  • User can switch between colour & grey-scale
  • Ability to select a range of hues the render uses
  • Possible to change the saturation and lightness of colours used
  • Ability to rotate the canvas
  • Change the width and height of the render area
  • Select from a set of zoom / position presets
  • A version using the Web Workers API in Firefox 3.5+ (See notes below on usage)

Note: As I mentioned above I have created a version using the Web Workers API found in Firefox 3.5+, but I strongly recommend using the standard version; I created it to see what difference it would make to the render time.

As it is, it makes no difference, in fact it actually makes it worse. The iteration calculation has been offloaded to a worker thread, the worker compiles the data then sends it back to the window. The window then loops through this the data and renders the image since worker threads don’t have access to the DOM for security reasons. This rendering tends to slow the browser down making the UI very slugish. I’ve tried not to use a setTimeout(“function()”, 0), to allow the JavaScript engine to catch up as, but it looks like I may have to in future versions. View a version using the Workers API here.

Big thanks to Geoff for putting the original together. Sliders and event handling was added using jQuery and the excellent jQuery UI. Preview carousel function used jCarousel.

jQuery Plug-in: Simple Navigation Animation Stagger

It’s great when you run into old code that you’d completely forgotten about. While reviewing a couple of old sites I’d put together I ran into some old jQuery animation code the client had requested. I’ve used it on a couple of projects in the past, not always on the navigation; it can be used with any set of list items. So I popped it into a jQuery plug-in for quick deployment on future projects. View a demo or download.

jQuery.staggerNaver simply delays each fadeIn animation on a set of list items to create a type of ‘wave’ effect. The plug-in can accept an object with custom user settings:

1
2
3
4
5
6
7
8
9
//Plug-in usage
jQuery(function($){
    $("#ourULorOL").staggerNaver({
        animateTime: 150,
        easing: "swing",
        onePageOnly: false,
        onePageSelector: "#home"
    });
};
  • animateTime: Time taken for fadeIn animation in milliseconds (default: 210)
  • easing: Easing method used, requires the easing plug-in if not default (default: “swing”)
  • onePageOnly: Use only on one page e.g. your home page (default: false)
  • onePageSelector: If you are only using the animation on one page, what selector would identify to jQuery that you are on that page? (default: “#home”)

I’ve included the one page only setting because as with any set of page animation it can sometimes become very annoying, especially if it does it on every page load!

View a demo or download (version 0.1 – updated 25th Feb 2010).

jsFiddle: My new favourite website

Every so often you come across a site that is so amazingly obvious that you think “why didn’t I think of that!”, jsFiddle is one of those sites. It allows you to paste your HTML, CSS and JavaScript code, and view the result all in the same page…simple! There are other sites out there that do the same such as Jsbin, but they just don’t do it as well.

My favourite feature that really stands out is being able to include one of the many popular JavaScript library’s by simple toggling a drop-down box; it even has different versions of each library to choose from. This is a really handy feature if you are a plug-in developer; keep your plug-in code in jsFiddle and quickly see if the latest version of the library breaks it.

jsFiddle code snippet GUI

Quickly view your code change at the touch of a button

Library’s included so far are:

  • Mootools Core
  • jQuery
  • Prototype
  • YUI
  • BBC Glow
  • Dojo
  • Processing.js

A couple of other features available are the easy to access code examples for each library and ability to run Ajax requests directly in the page. It’s like a mini IDE in your browser, all it needs now is an error console; maybe that is on their to-do list. If you don’t use JavaScript library’s and just want vanilla JavaScript, they have that option too.

As an example I’ve added my charactersLeft jQuery plug-in to jsFiddle, take a look here. Very cool huh!

The append and appendTo jQuery methods

With every new release of jQuery more and more features are added. A set of features I use all the time for manipulating the DOM are the prepend() and append() methods. In addition to these methods you also have prependTo() and appendTo(); they vary slightly in the fact that you create your new content first, then choose an element to add it to:

1
2
3
4
5
6
7
8
//Create our content   
var appendHTML = "<p>I'm going to be added to the DOM</p>";

//Select our element, then add the html    
$("#container").append(appendHTML);

//Create our content, then select the element to append to
$(appendHTML).appentTo("#container");

Prep-end works exactly the same only it adds the content as the first-child of the container rather than the last-child.

With version 1.4 of jQuery came a great addition to both methods;they can now accept a function which returns the index in the current set of elements, and the original HTML string of the element. The addition allows you to loop through a whole set of elements and easily add content to the beginning / end whilst including the original content:

1
2
3
4
5
6
7
8
9
10
11
//Loop through all <p> tags and prep-end "I love jQuery."
$("p").prepend(function(index, html){
    var newHTML = "I love jQuery. " + html;
    $(this).html(newHTML);
});

//Loop through all <p> tags and append ", now with added spice!"
$("p").append(function(index, html){
    html += ", now with added spice!";
    $(this).html(html);
});

Very handy! I’ve put together a little demo to demonstrate this functionality in action.

Currently on page 3 of 512345