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:
- walk the dom and perform an action on every form object input type=submit (every instance of a submit button on the page)
- for each instance, calculate the length of the "value" attribute (the text in the submit button)
- 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.
Posted by Stéphane Deschamps | January 3, 2008 4:40 PM
Posted on January 3, 2008 16:40