For fun I asked a few friends for ideas on a random color generator in a single line of javascript. You know, these guys: #0afec0, #c9f2d0, #9b923e.
Here's what we came up in about two minutes (in chronological order)…
'#' + (function co(lor){ return (lor +=
[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)])
&& (lor.length == 6) ? lor : co(lor); })('');
Similar recursive technique, but using a string instead of an array and aliasing the Math object:
(function(m,s,c){return (c ? arguments.callee(m,s,c-1) : '#') +
s[m.floor(m.random() * s.length)]})(Math,'0123456789ABCDEF',5)
Using a named function expression instead of arguments.callee.
'#'+(function lol(m,s,c){return s[m.floor(m.random() * s.length)] +
(c && lol(m,s,c-1));})(Math,'0123456789ABCDEF',4)
If we assume JavaScript 1.6, then we could just use Array.map():
'#'+'0123456789abcdef'.split('').map(function(v,i,a){
return i>5 ? null : a[Math.floor(Math.random()*16)] }).join('');
But then, the magic of Math struck (16777215 == ffffff in decimal):
'#'+Math.floor(Math.random()*16777215).toString(16);
Thx to ben alman, nlogax, and temp01 for their smarts.
Paul Irish javascript
There are a few things that a console.log wrapper can and should do:
- Prevent errors if a console isn't around (i.e. IE)
- Maintain a history of logs, so you can look in the past if your console is added afterwards (e.g. firebug lite)
- Normalize the browser differences in console integration (e.g. when passing multiple arguments into
console.log())
- For something you type regularly, make it quicker to type for the lazy among us.
But there are a few considerations…
Console.log.apply doesn't handle multiple arguments work in Safari 3 or Chrome 1.1
Firebug, Chrome, and Safari have a clearer presentation for strings when inside an array: 
However while the improved array-wrapped presentation is nice, nested arrays get truncated: 
Truncation is no good, so here we avoid array-wrapping when we can.
Extra features
- A reverse-chronological history, accessible as an array at
log.history
- I have also included a shorthand
logargs() function that is useful when you're inside a function and want to know the context and arguments passed in. I use it a lot in ajax callbacks. Worth noting that it uses arguments.callee.caller, which will be deprecated in ECMAScript 5 Strict mode. :(
The code:
window.log = function(){
// store logs to an array for reference
log.history = log.history || [];
log.history.push(arguments);
window.console && console.log[console.firebug ?
'apply' : 'call'](console,Array.prototype.slice.call(arguments));
}
// logargs(this); == console.log(this,arguments);
window.logargs = function(context){
// grab the calling functions arguments
log(context,arguments.callee.caller.arguments);
}
And if you'd like it minified:
window.log=function(){var a="history";log[a]=log[a]||[];log[a].push(arguments);window.console&&console.log[console.firebug?"apply":"call"](console,Array.prototype.slice.call(arguments))};window.logargs=function(a){log(a,arguments.callee.caller.arguments)};
Interestingly, the minified version of this script is smaller (262 bytes), and arguably more useful, than the minified firebugx.js, which I've covered before. Plus it has quite a few more features.
Demo?
log() and logargs() demo
Plus Firebug lite?
You got it. This bookmarklet will add firebug lite, and then output the logged history when it's ready:
>>> Fbug Lite+log <<<
Want more power?
After writing this, I worked with Ben Alman on a more comprehensive and robust logging script. It's excellent if you take full advantage of the console API. And you should be aware that Safari 4 and Chrome 2 have most of that API supported. Make full use of it and don't you dare type another alert()!
Paul Irish javascript
There are a few cases where you want to know if the user is idle. Namely:
- You want to preload more assets
- You want to grab their attention to pull them back
- You want close their banking session after 5 minutes of inactivity. (Jerk!)
- You want the site to sneak off the screen and see if they notice ;-)
Nick Zakas wrote a script for YUI3 to handle these cases. His writeup has a great description of the architecture approach he took to the script.
In my jQuery adaptation, I did a few different things:
- Leveraged event namespaces for easy unbinding
- Considered mousewheel as activity, in addition to keyboard and mouse movement.
- Gave it a bit more jQuery-ish of an API
To use:
// idleTimer() takes an optional argument that defines the idle timeout
// timeout is in milliseconds; defaults to 30000
$.idleTimer(10000);
$(document).bind("idle.idleTimer", function(){
// function you want to fire when the user goes idle
});
$(document).bind("active.idleTimer", function(){
// function you want to fire when the user becomes active again
});
// pass the string 'destroy' to stop the timer
$.idleTimer('destroy');
Get the source on github (4.6k unminified)
View the demo
Note: If you want to change the timeout interval, you'll have to destroy the existing timer first.
Paul Irish jquery
I don't use CSS hacks anymore. Instead I use IE's conditional comments to apply classes to the body tag.
Nonetheless, I wanted to document every browser-specific css selector and style attribute hack I've seen. Plus there's no way to provide stylesheets to only Safari, I believe.
So here are go:
Comprehensive List of Browser-Specific CSS Hacks
/***** Selector Hacks ******/
/* IE6 and below */
* html #uno { color: red }
/* IE7 */
*:first-child+html #dos { color: red }
/* IE7, FF, Saf, Opera */
html>body #tres { color: red }
/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body #cuatro { color: red }
/* Opera 9.27 and below, safari 2 */
html:first-child #cinco { color: red }
/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: red }
/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete { color: red }
/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho { color: red }
/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
#diez { color: red }
}
/* Safari 2 - 3.1 */
html[xmlns*=""]:root #trece { color: red }
/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=""] #catorce { color: red }
/* Everything but IE6-8 */
:root *> #quince { color: red }
/* IE7 */
*+html #dieciocho { color: red }
/***** Attribute Hacks ******/
/* IE6 */
#once { _color: blue }
/* IE6, IE7 */
#doce { *color: blue }
/* Everything but IE6 */
#diecisiete { color/**/: blue }
/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }
/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }
If you'd like to take a gander by yourself:
Test page with all these hacks present.
View the test page at browsershots.org
(Thx to Webdevout, Evotech, and Jeffrey, and commenters.)
I should point out I'm not including weird hacks like the voice-family ones or anything particularly ugly.
Somewhat related…
Here are the most concise browser sniffs I've seen. (Not that browser sniffing is good or anything…)
Update 2009.06.03 - I added the suggestions left
on Ajaxian and in the comments and updated the browser versions to consider Safari 4, IE 8, and Chrome 2.
Paul Irish front-end development
For April Fools day, Youtube enabled you to view any page and video, totally upside down.

Pretty cute and clever, so I unapologetically stole their code and re-appropriated it as a jQuery plugin. As you can see, I have very valuable time. :-p
Download: jquery.textflip.js 1.4K
Demo: Click me to flip all this posts text
Paul Irish jquery
On a recent project I took my previous approach to automating firing of onload events to a new level.
For instance if your code was architected in an object literal such as:
FOO = {
common : {
init : function(){ ... },
finalize : function(){ ... }
},
shopping : {
init : function(){ ... },
cart : function(){ ... },
category : function(){ ... }
}
}
A page with this body tag:
<body id="cart" class="shopping">
would load these functions sequentially:
UTIL.fire is calling: FOO.common.init()
UTIL.fire is calling: FOO.shopping.init()
UTIL.fire is calling: FOO.shopping.cart()
UTIL.fire is calling: FOO.common.finalize()
In addition, using these classes and IDs on the body tag provides some excellent specific hooks for your CSS.
The javascript:
UTIL = {
fire : function(func,funcname, args){
var namespace = FOO; // indicate your obj literal namespace here
funcname = (funcname === undefined) ? 'init' : funcname;
if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
namespace[func][funcname](args);
}
},
loadEvents : function(){
var bodyId = document.body.id;
// hit up common first.
UTIL.fire('common');
// do all the classes too.
$.each(document.body.className.split(/\s+/),function(i,classnm){
UTIL.fire(classnm);
UTIL.fire(classnm,bodyId);
});
UTIL.fire('common','finalize');
}
};
// kick it all off here
$(document).ready(UTIL.loadEvents);
This system worked very well and keeps you in serious control of the execution order.
In the end, I used this plus a custom event to bind super low priority script.
For example:
$(document).bind('finalized',function(){ ... }); // placed within a FOO.shopping.category()
And I'd trigger that
$(document).trigger('finalized');
at the very end of UTIL.loadEvents(). This allows you to keep similar code together, but delay portions responsibly without any setTimeout ugliness.
Paul Irish javascript, jquery
No doubt you've heard that Cornifying is the latest and greatest invention of the internet.
Now you can surreptitiously add it to your own sites, joining The Underground Cabal of Mirthful Protectors of the Corn:
var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
$(document).keydown(function(e) {
kkeys.push( e.keyCode );
if ( kkeys.toString().indexOf( konami ) >= 0 ){
$(document).unbind('keydown',arguments.callee);
$.getScript('http://www.cornify.com/js/cornify.js',function(){
cornify_add();
$(document).keydown(cornify_add);
});
}
});
After a user hits the Konami code (up,up,down,down,left,right,left,right,b,a), every other keystroke will add happiness to the world.
You'll find this website has already been enabled. Try it out. :)
Update 2009.04.27: It was discovered today
ESPN.com was hiding some unicorns under its konami. (
kotaku coverage) In fact it had been up there for weeks. :)
Paul Irish jquery
A site I'm currently working has had boring and barren error pages. Until now!
I wanted some images from failblog.org to liven things up a bit. In a quick 20 minute hack, I took the site's rss feed, parsed it for the right content using Yahoo Pipes, exported as JSON-P, pulled that in with jQuery, and displayed a random image.
Here's the pipe I'm using:

The trick to pulling in Yahoo Pipe data via JSON-P is by adding a "_callback" argument, defining the callback function name.
The script:
jQuery.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=0vxHL0Lo3RGc2uL8pQt1Yg&_render=json&_callback=FailImages&callback=?');
function FailImages(data){
var imgs = data.value.items;
if (imgs){
var url = imgs[Math.floor(Math.random()*imgs.length)].url;
jQuery('< img src="'+url+'">').insertAfter('h1');
}
}
The result:

And of course..
Demo page
Paul Irish front-end development, jquery
I've been a big proponent of Jing for screencapture for a while. I still love it, and it's top notch for sharing video, but I've come to enjoy a free tool called Gyazo for screenshots. Both of these tools are invaluable when it comes to web development QA.
Below you'll see a screencast demonstrating gyazo to the #jquery IRC channel:
Both Jing and Gyazo provide hosting for you (infinite, eternal store, as far as I've seen), and they both automatically copy the url to your clipboard. Gyazo is a bit quicker for images, and also doesn't have a business model, which is comforting. :)
And it's cross-browser as long as you don't mind some Japanese text:
Oh and open source. :) I think you can even host your own image repo if you don't want to use gyazo.com.
Handy tip, keep the shortcut somewhere totally handy. On Windows, I keep mine with the quick launch icons.
Paul Irish front-end development, hacks
From what I've seen a good number of developers these days are split between conditional stylesheets and css hacks.
You're used to seeing this:
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
<!--[if IE 7]><link rel="stylesheet" type="text/css" media="screen" href="css/ie7.css" />< ![endif]-->
<!--[if IE 6]><link rel="stylesheet" type="text/css" media="screen" href="css/ie6.css" />< ![endif]-->
But probably also plenty of this:
div.infoBox { float: left; padding-right: 10px; _padding-right: 5px; }
CSS hacks to target specific browsers stay where the rest of your styles are, but they certainly don't validate. For sometime now, the standards community has rallied around conditional stylesheets as a solution to the validation problem.
There are a few problems with it though:
- Conditional stylesheets mean 1 or 2 additional HTTP requests to download
- As they are in the the <head>, the rendering of the page waits until they're totally loaded.
- Also - Yahoo's internal coding best practices do not recommend conditional stylesheets
- It can separate a single CSS rule into multiple files. I've spent a lot of time wondering "Where the eff is that rule coming from!?" when it turned out to be tucked away in a conditional stylesheet.
Here's my proposed solution:
<!--[if lt IE 7 ]> <body class="ie6"> <![endif]-->
<!--[if IE 7 ]> <body class="ie7"> <![endif]-->
<!--[if IE 8 ]> <body class="ie8"> <![endif]-->
<!--[if !IE]>--> <body> <!--<![endif]-->
Using the same conditional comments, we're just conditionally adding an extra class onto the body tag. This allows us to keep our browser-specific css in the same file:
div.foo { color: inherit;}
.ie div.foo { color: #ff8000; }
Plus it totally validates and works in all browsers.
(Hat tip to Paul Hammond and Adam McIntyre for being s-m-r-t.)
Paul Irish front-end development