The YUI Compressor is a phenomenal tool to minimize (and obfuscate, by the way) CSS and JavaScript code.
Here’s a little bash script that will batch-process all JS and CSS files in your project, while preserving a source copy of that file.
#!/bin/bashJAVA="$(which java)"BUILDDIR="$(pwd)"YUIJAR="/path/to/yuicompressor-x.x.x.jar"echo"Compressing JS and CSS:"for TYPE in js css
dofor FILENAME in $(find"$BUILDDIR"-iname"*.$TYPE"|sed-e"s|\.$TYPE$||g")doecho-n"compressing $FILENAME.$TYPE ... "mv"$FILENAME.$TYPE""$FILENAME.src.$TYPE"$JAVA-jar$YUIJAR--charset utf-8--type"$TYPE""$FILENAME.src.$TYPE">"$FILENAME.$TYPE"if["$?" == '0']; thenecho"success."elsecp"$FILENAME.src.$TYPE""$FILENAME.$TYPE"echo"ERROR: failed, using original."fidonedoneecho"done."
Note: You will usually first copy your application source to some sort of build target, and then apply this script. Elsewise, you will have to revert the actions of that script when you continue editing your code.
There are some handy functions in PHP you would sometimes like to have in JavaScript, too. Why not reimplement them? It’s not hard. Take for example in_array() and explode():
Hint: On many pages of PHP functions, there are comments which describe how to reimplement a function (e.g. PHP 4 implementations of PHP 5 functions) — in PHP though, but it’s easy to adapt them for JavaScript.
If you have have a select form element with a size attribute, one common option for the user is to leave it empty (especially in combination with multiple). The problem is, as soon as one or more options are selected, it is quite impossible in most browsers, to not select anything at all. And even if there is a way, it is not easy to accomplish. Try for yourself to deselect all items:
With a little JavaScript magic, we can offer a button to clear the select field:
function nl_clear_select(element){var opt_length = document.getElementById(element).options.length;for(var i =0; i < opt_length; i++)
document.getElementById(element).options[i].selected=false;}
Now try again to clear the select field. Hint: clicking on "Clear selection" will help a lot.
Here’s how to get the currently checked value of radio button section. The parameter elementName is the name attribute of the radio input.
function getRadioValue(elementName){var i, element = document.getElementsByName(elementName);for(i =0; i < element.length; i++)if(element[i].checked==true)return element[i].value;}