Some DOM elements are visually annoying, for example a long list, we may want to only show a small part of the element, and expand to full length when the mouse is hovering on it. Its a simple script, we want the smallest javascript footprint, we don't use jQuery. With some decent micro pieces of javascript snippet, wen can implement our feature without big monolithic javascript framework.

What we need is a DOM selector engine, an event register function and a dom ready function.

1. DOM ready function

We need a function similar to jQuery's $.ready function, I select the onDomReady. Its based on jQuery's implementation, but its independent. Here is a simple example how to use it:

 
onDomReady(function(){
(function(){
    alert('hello, world');
})();    
});
 

2. A CSS selector engine

No one wants to use the raw javascript like getElementById or similar API to select DOM elements. We need a decent and light weight CSS selector engine. The first one I tried is saltjs, its really small, but it cause errors on my IE 8 browser.

Then I found another engine: nut. And it works fine.

3. Event register

The only thing we need actually is the addEvent function. There is no single micro js library focus specifically on event handling, what I found is this snippet provided by the author of jQuery addEvent() recoding contest entry. Its decent, concise and with such a little size. The only thing we need to do is copy and paste and use it.

4. Combine together

Based on the components above, we can implement the toggle function as follows:

 
onDomReady(function(){
(function(){
    function toogleCat(){
        var ele_arr = selector('.cat-box');
        var ele = ele_arr[0];
        var overflow = ele.style.overflow;
        if(overflow == "hidden") {
            ele.style.maxHeight = "";
            ele.style.overflow = "auto";
        } else {
            ele.style.maxHeight = "100px";
            ele.style.overflow = "hidden";    
        }
    }
    toogleCat();
 
    addEvent(selector('.cat-box')[0], 'mouseenter', toogleCat)
    addEvent(selector('.cat-box')[0], 'mouseleave', toogleCat)
 
})();
});