Dug has a new mobile number. Please note: +44 75 15 66 16 55

« links for 2007-12-29 | Main | Subverting from within »

The amazing shrinking javascript

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:-)

Comments (1)

Dug,

The if/then you're referring to is called a ternary operator.

It goes like this:

myVar = (testing expression) ? value_if_true : value_if_false;

Then it's just a bit more complicated but you can embed one test in another.

Actually it's quite old, I kind of remember writing MS Excel formulas like this 15 years ago. But it's very elegant once you get the hang of it.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on January 1, 2008 6:21 PM.

The previous post in this blog was links for 2007-12-29.

The next post in this blog is Subverting from within.

Many more can be found on the main index page or by looking through the archives.

Website Metrics and Site Statistics by NextSTAT