The amazing shrinking javascript

dug dug Follow Jan 01, 2008 · 1 min read
Share this

OK, so I occasionally hack some bits of Javascript around to see if manipulating bits of the DOM can produce interesting, unusual or accessible interactions… These last couple of years I’ve started looking at frameworks and libraries which on the whole make the job a lot nicer (from Dojo to Prototype via jQuery and Mootools).

So anyway, here’s a nice example I was sent by one of the brainy bunch on the jQuery list. Here’s the requirement I started writing with:

  1. walk the dom and perform an action on every form object input type=submit (every instance of a submit button on the page)
  2. for each instance, calculate the length of the "value" attribute (the text in the submit button)
  3. assign a class to each submit button on the basis of the size of the above value attribute

That is one big-ass script with loops a gogo and a bunch of “if then else” constructs no? Well, this guy has done it in a script which is only 107 (one hundred and seven) characters long:

$('input:submit').each(function(){ var len=this.value.length; $(this).addClass(len<5?'S':len>20?'L':'M');});

It’s both confusing and wonderful and I’m still trying to understand exactly how the whole thing works but if you’re interested in this sort of stuff here’s the example page

Ta very much Mr Wizzud:-)

Join Newsletter
Get the latest news right in your inbox. We never spam!
Written by dug Follow
Hiya, life goes like this. Step 1: Get out of bed. Step 2: Make things better:-)