Posted in 'Code Snippets, JavaScript' by James on December 16th, 2009
A while ago I wrote a little “pulse” plugin for jQuery which would make an element pulse between two or more states. I won’t bother linking to it because it’s offline. I decided to have another go at developing it, this time with a more refined and intuitive API.
I’ve tried to emulate the characteristics of jQuery’s animate() method as much as possible. There are only a few slight differences. Here’s a typical call to the new “pulse” plugin:
jQuery(element).pulse({
opacity: [0, 1],
backgroundColor: ['red', 'yellow']
}, 1000, 5, 'linear', function(){
alert("I'm done pulsing!");
});
It’s almost exactly the same parameter pattern as animate(), except that you have to specify an array of values for each CSS property, and also an additional numerical parameter, after the duration, which signifies how many times you want the pulse to run (the above code will run the pulse five times).
It also works with an “options” object, just like animate():
jQuery(element).pulse({
opacity: [0,1]
}, {
duration: 100, // duration of EACH individual animation
times: 3, // Will go three times through the pulse array [0,1]
easing: 'linear', // easing function for each individual animation
complete: function() {
alert("I'm done pulsing!");
}
});
You should note that the duration option only defines how long each individual animation will run, not the entire pulse. To dictate the length of the entire pulse you need to use the times option. Also note that the times option refers to an entire run-through of the largest array found in the properties option.
You can “pulse” through as many values as you want:
jQuery(element).pulse({
backgroundColor: ['red', 'yellow', 'green', 'blue'],
opacity: [0, 1],
});
The arrays don’t all have to be of equal length – with the above code, the opacity would keep changing as is defined by its array.
The plugin itself is quite small. I’ve decided to start a new repo at Github, just for small and useful jQuery plugins like this.
Pulse plugin on Github
I haven’t tested it extensively yet, so, as usual please notify me of any bugs/issues. Thanks!
Posted in 'JavaScript, News' by James on December 11th, 2009
I want to say a huge Thank You to everyone that entered the cookbook competition! It was very interesting reading through all your comments; some funny, some saddening, some very insightful and others just plain silly!
I was considering picking the winners based on the comments themselves, but after considering the sheer number of comments (over 250) and the fact that there are many more than five people that genuinely deserve a free copy, I decided to pick the winners randomly!
So, without further delay, here are the five winners (see the code that picked them):
-
Going to leave a word here to try my luck. I could use some more learning. I should have created a plug in by now, maybe the book could help me get there.
-
Hi. Thanks for this possibility! I would like to win this book to gain a better and deeper understanding of jQuery. I am trying to make the best use of the online examples many sites offer, but I am still a bit “old fashioned” and still need a good printed book to highlight, comment, carry with me and draw funny faces on when I’m learning something
-
I have a craving for some jQuery and I have no recipe to go by. Why use the frozen microwave jQuery you find on the web, when you can have fully baked goodness printed and bound? I want to have a great reference for my daily jQuery needs. It makes javascript something special.
-
Because I haven’t read it yet?
-
We love jquery and need to get better at it. Being a small, non-profit, public radio station, any money i can save our .org on books… is always good!
Congratulations to these commenters! I’ll be emailing you within the next day!
I know that some of you would have preferred me to pick the comments based on the contents of each comment, but it just wouldn’t have been feasible. There were so many great comments – it would have been impossible to fairly decide.
Once more, congratulations to the lucky winners!
Posted in 'Cool Stuff, JavaScript' by James on December 8th, 2009
The jQuery cookbook is a recently released book from O’Reilly that covers all aspects of jQuery and tackles common client-side quandaries with a well-thought out arsenal of recipes. This book will empower beginners and veteran’s alike, allowing you to be truly confident in your jQuery skills.
Update: The competition is now closed. (see the winners)
The book has been written by many different authors, all of whom play a significant role in the jQuery community:
Give away!
O’Reilly has been kind enough to offer two free copies of this fantastic book for me to give away on my blog. To enter this small competition, simply leave a comment with a sentence or two saying why you need/want this book. I wish I could give you all free copies, but unfortunately I can only pick two winners, so think carefully about what you write.
Don’t forget to enter an email address (confidential) in the comment form so I can contact you if you win. CONTEST CLOSES 20:00 GMT Wednesday (9th December) (see update)
Posted in 'JavaScript' by James on December 4th, 2009
At first, it was mysterious and stylish, then it became regular, and now it’s just mundane! The usage of “self-invoking anonymous functions” is what I’m talking about. You know what I mean; it’s this:
(function(){
// I'm cool
})();
Recently, I even managed to convince my poor brain that using many of these constructs amounted to maintainable and cool-looking code. I even thought that this:
function Constructor() {
}
Constructor.prototype.fn = function(){};
… was ugly enough to require a bit of self-invoking cool’ness:
var Constructor = (function(){
function Constructor() {
}
Constructor.prototype.fn = function(){};
return Constructor;
})();
What was I thinking?? … Well, I’ll tell you: I was trying to create the illusion of containment! I didn’t want the fn method declaration to be left astray, departed from its parent (the constructor).
When used in this way, the Self Invoking… cool’ness creates an entirely pointless closure, that only serves to comfort the human programmer. Its similar to this:
var fruits = "banana apple orange grape strawberry".split(' ');
Compared with the less-cool more-logical version:
var fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry'];
So, they both end up exactly the same, but the former takes a while longer to actually produce the array upon interpretation. So, why exactly do we do this?
I know why I do it: it’s because I’m lazy; so lazy that I can’t even bring myself to type out an array of strings, even though doing so would result in a faster run-time! The cost of repeatedly reaching for the awkwardly placed ' or " on my keyboard, to type out the array, is obviously just too much for me to bare!
Maybe you don’t do it… but it is out there!
// From jQuery 1.3.2
"ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(",")
Let’s compare that to the typed out array:
['ajaxStart','ajaxStop','ajaxComplete','ajaxError','ajaxSuccess','ajaxSend']
By typing it out the former “cool” way we save a total of ONE character! Worth it?
Do you have any “anti-patterns in the making” to share?
Note: Obviously, there are situations where a self-invoking cool’ness (what I will call them from now on) might be useful. For example, the module pattern, or that ol’ (function($){})(jQuery); trick.
Posted in 'JavaScript' by James on December 2nd, 2009
SiteTraverser is a JavaScript class1 which you can use to create bookmarklets that crawl websites looking for the presence or lack of certain features.
Here’s an example that utilises SiteTraverser (give it a click!):
Click to traverse!
All it does is list the titles of some pages on this site. The code behind the bookmarklet is quite simple:
var s = document.createElement('script'),
t = setInterval(function(){
if ( window.SiteTraverser ) {
// Script is loaded
clearInterval(t);
s.parentNode.removeChild(s);
// Let's start traversing
new SiteTraverser({
// Just for this demo, we're specifying the URLs.
// Normally, SiteTraverser would just crawl in all directions.
urls: ['/foo/1.html','/foo/2.html','/foo/3.html'],
check: function(source, url){
var titleMatch, title;
if ( titleMatch = source.match(/<title>(.+?)< \//) ) {
return this.success(
"Title found: " + '"' + titleMatch[1] + '"',
"URL: " + url
);
}
return this.failure("No title :(");
}
}).go();
}
}, 100);
s.src = 'http://qd9.co.uk/projects/SiteTraverser/sitetraverser.js';
document.body.appendChild(s);
First, we load sitetraverser.js, and then we continue to instantiate (new SiteTraverser()) and run it (.go()).
Posted in 'Cool Stuff, JavaScript' by James on November 20th, 2009
A while ago I posted a funky demo that made use of the canvas tag to show the effects of all the available jQuery easing functions. jQuery allows you to specify an easing function whenever you initiate an animation. jQuery will use your selected easing function to govern the progression of that animation.
Currently, it’s not possible (within the confines of the current API) to have separate easing functions running on separate properties within a single animation. Obviously, you can run two animations at the same time (with different easing functions) by disabling queueing, but they’re not really in sync – one is slighly ahead of the other.
So, this is a regular animation, with one easing function:
$(myElement).animate({
left: 500,
top: 500
}, 'easeOutExpo');
It’s a pretty average animation, the easing function effects both properties (top and left) so the element moves in a straight line, with a slight slow-down at the end.
I’ve had a go at modding the animate() method so it’s possible to specify an additional easing function for each individual property, like so:
// prop: [duration, easing]
$(myElement).animate({
left: 500,
top: [500, 'easeOutBounce']
}, 'swing');
In this example, the overall progression of the animation is governed by the swing easing function*. But, in addition to that, the top property is being governed by the easeOutBounce function.
* – It’s set to swing by default anyway; I’m being explicit for the sake of the example.
Have a look at the resulting effect! It’s pretty cool!
As I said before, a similar effect can be achieved with two animations and the queue option being set to false, but the modded animate() method actually allows more than that; it allows you specify a “base” easing function which will handle the overall progression of the animation, and an additional easing function to govern the progression of a single property. It’s like overlaying easing functions; the result of one is the input of another.
Posted in 'Accessibility, JavaScript, Usability' by James on November 16th, 2009
I am a strong proponent of layered cakes. I don’t know how to handle a cake that is just mashed together with many ingredients and shoved in the oven — I just end up staring at it, wondering how the hell I’m meant to consume this thing! I prefer to have clearly defined layers, each with a unique palette that, when combined with the other layers adds to the overall symphony of taste.
Of course, I’m not actually talking about bakery; I’m talking about the web, and the many layers that it’s made of. I believe that maintaining separate layers is the best way to move forward whilst offering a usable, functional and accessible web.
I think JavaScript is an afterthought, and I think it’s best for everyone if it’s treated that way. Once you try mixing it into your application you’ll eventually encounter a conflict of layers! A.K.A pissed off users.
I’m not just talking about being unobtrusive; I’m talking about true progressive enhancement, and true separation of concerns, on the server side and on the client side. I appreciate and try to develop by this ideal, because I honestly feel that it is the best way to develop any website or any application.
It’s not just about the end-user experience though; it’s about developing in a way that makes sense. For me, this makes sense.
For me, until I change my mind, JavaScript will always be the icing on the cake!
Posted in 'Code Snippets, JavaScript' by James on November 13th, 2009
In Thomas Fuchs’ latest JavaScript performance presentation he talks about the speed gains that can be experienced by using “unrolled” loops.
A conventional loop:
for (var i = 0; i < 10; ++i) {
doFoo(i);
}
The “unrolled” version of that loop:
var i = 0;
doFoo(i++); doFoo(i++); doFoo(i++); doFoo(i++); doFoo(i++);
doFoo(i++); doFoo(i++); doFoo(i++); doFoo(i++); doFoo(i++);
A partially unrolled version:
for (var i = 0; i < 10; ) {
doFoo(i++);
doFoo(i++);
doFoo(i++);
doFoo(i++);
doFoo(i++);
}
Interestingly, speed gains can be experienced dependent on the loop size, albeit marginal at best. I thought about ways to build this into a clever forEach function and came up with something that ‘pre-compiles’ functions containing partially unrolled loops. Have a look:
var forEach = (function() {
var fns = [],
callers = "true",
numberFn = 10,
i = 1;
for ( ; i <= numberFn; ++i ) {
callers += "&&f(a[++i])!==false";
fns[i] = new Function("a", "f", "l", "var i=0;while (i<l) {"+callers+"}");
}
return function( array, fn ) {
var len = array.length,
n = numberFn, i;
while (i = n--) {
if ( len % i === 0 ) {
return fns[i](array, fn, len);
}
}
};
})();
This function will run one of 10 ‘pre-compiled’ functions on the passed array, dependent on the highest factor of the array’s length. I’m only creating 10 different functions in this example, you could create more.
If you were to pass an array with a length of 14, then fns[7] would be used, since 7 is the highest available factor (the highest number below 10 that 14 can be divided by, to gain a whole number). fns[7] looks something like this:
function anonymous(a, f, l) {
var i = 0;
while (i < l) {
true &&
f(a[++i]) !== false &&
f(a[++i]) !== false &&
f(a[++i]) !== false &&
f(a[++i]) !== false &&
f(a[++i]) !== false &&
f(a[++i]) !== false &&
f(a[++i]) !== false;
}
}
The !== false part is used to create the effect of loop-breaking. Notice that the success of this boolean expression is depended upon to continue the chain of expressions (a && b && c)
I’ve only tested it briefly, and to be honest, there doesn’t seem to be a notable benefit. In IE, I can see a bit of improvement over the conventional forEach implementation but only if I’m using arrays with 1000+ lengths. I think this would only be useful in situations where you absolutely have to squeeze every inch of potential performance out of your app. Anyway, it’s still pretty interesting, I wonder what other fancy things can be created by using pre-compiled functions.
Posted in 'JavaScript' by James on October 31st, 2009
For those of you who are looking to take that next step in your steady uptake of the jQuery library, I can absolutely recommend Cody Lindley’s latest creation, “jQuery enlightenment“! It’s a breath of fresh air to be honest! It’s an overview of the jQuery library containing code samples (all available through JSBin.com), notes from the author and many applicable techniques.
- Core jQuery – all the foundation stuff is covered in this chapter, but Cody doesn’t hold back – he explains everything in considerable detail.
- Selecting – the various ways to select elements are outlined here, plus a couple of common problems are addressed, such as “selecting elements by searching attribute values using regular expressions”.
- Traversing – an overview of some of the available DOM traversal methods.
- Manipulation – covers the basics of element manipulation.
- HTML Forms – quite an exhaustive chapter that details the techniques used to work with forms in jQuery.
- Events – an overview of how jQuery manages events plus some applicable examples.
- jQuery and the web browser – A couple of useful snippets.
- Plugins – how to create them, best practices, useful advice.
- Performance best practices – Some useful advice for the performance conscious developer.
- Effets – An introduction to jQuery’s animation capabilities, plus a couple of helpful tips regarding its usage.
- Ajax – A brief overview of jQuery’s XHR capabilities (plus JSONP)
- Miscellaneous concepts – Useful advice that doesn’t quite fit into any of the above chapters.
Beginners and intermediate level jQuery coders will benefit from this book. Even if you’re ‘advanced’ you might pick up a couple of things. Purchasing a PDF copy is only $15, which seems a reasonable price to me, plus a portion of that goes directly to the jQuery project itself!
From the introduction:
jQuery Enlightenment was written to express, in short-order, the concepts essential to intermediate and advanced jQuery development. Its purpose is to instill in you, the reader, practices that jQuery developers take as common knowledge. Each chapter contains concepts essential to becoming a seasoned jQuery developer.
Pick up a copy!
Posted in 'JavaScript, My Life' by James on October 29th, 2009
For those of you that don’t know, I’m currently studying Computer Science at the University Of Kent. As our first programming assignment we had to create a game of Pong (see screenshots here) using Java and a 2D-graphics platform called Greenfoot. It was a challenging and interesting assignment, within which I was able to discover many new things about Java and about general game development.
In my opinion, Java’s insistence on a class based approach makes it a fantastic programming language to start with, albeit being quite hefty, in terms of the sheer quantity of available classes. I also liked the fact that most of my knowledge of JavaScript could be applied to Java. There are a few syntactical discrepancies that left me confused, but all the foundation concepts were (more or less) the same.
I thought it’d be fun to port my Pong game over to JavaScript. It was painlessly quick to do actually, and it’s the first time I’ve ever built a game with JavaScript and the HTML5 canvas tag/API. You can head over to the demo to play it for yourself, and feel free to have a look at the source code. It’s not quite as sophisticated as the Java one, I didn’t have time to add cool graphics or a scoring mechanism. And yes, I know it’s the wrong way round – we were told to do it that way!
What I discovered
It’s a frame-by-frame thing
One of my very first revelations was that, to create a game, it’s important to think about everything on a frame-by-frame basis. Every new frame is a fresh slate upon which you reflect the various states represented in your program. The relationship between any two frames depends on a persisting programmable interface that “remembers” previous states.
It all becomes wonderfully simply when you think about it in this way… move the ball one cell to the left, if its position is equal to zero then it must be at the left wall, therefore we can bounce it off the wall! (okay, so it’s not actually that simple – you have to take the ball’s width into account)
It’s a massive contrast from ‘event-driven’ development, wherein you wait for the user to make a choice and then carry out something following that. In the Pong game, I’m not waiting for the user to do anything – on every new frame I simply query the necessary information to make stuff happen. For example, If the left cursor key is currently down then move this (paddle) one cell to the left! (I’m not waiting for the user to press the left cursor key, each frame is being drawn regardless.)
Everything’s an object
In my Pong game, each physical object in the game is represented as an object within the programmable layer, each one an instance of a predefined class. For example, there’d be one Paddle class from which two Paddle instances (“objects”) would be created, each representing a single physical paddle on the screen.
OOP really shines here!
Abstract, but not too much!
Abstraction really is very important, especially when there are tonnes of things that need to be happening at any time. What I actually mean here, is that it’s important to separate out functionality between your methods. This is obviously better: