Musings of a Fondue

JResig Book - TIL

Today I learned that you can abstract away frequently used code.

While working through John Resig’s book Pro JavaScript Techniques, I noticed he uses simple helper functions to keep the code neat and non-repetitive.

For example, take the case of getting an element’s id. Resig writes this function,


function id(name){
    return document.getElementById(name);
}

Now anytime you need to get an element by its id, you just type


id("elementId");

Contrast this to having this all over your code,


document.getElementById("elementId")

Even better is when you are passing elements by id to functions. It now looks like this,


hide( id("overlay") );

Instead of this,


hide( document.getElementById("overlay") );

Cool!

Here are some other clever helper functions he uses,


/*
    hide(elem)
    show(elem)
    getWidth(elem)
    setWidth(elem)
    posX(elem)
    setX(elem)
*/

function hide(elem){
    //find out current display
    var curDisplay = getStyle( elem, 'display');

    //remember state for later
    if ( curDisplay != 'none')
        elem._oldDisplay = curDisplay;

    //hide the element
    elem.style.display = 'none';
}
function show(elem){
    //'block' if no previous display saved
    elem.style.display = elem._oldDisplay || 'block';
}
function getWidth(elem){
    return parseInt( getStyle( elem, "width" ) );
}
function setWidth(elem, num){
    elem.style.width = num + "px";
}
function posX(elem){
    return parseInt( getStyle( elem, "left" ) );
}
function setX(elem, pos){
    elem.style.left = pos + "px";
}

I’m tempted to rewrite my past projects using his style! I will definitely be applying it moving forward.

Comments