Need help refactoring a simple jQuery animation script

I have a status message box (div box) located at the bottom of a web page using position: fixed; and below: 0;. Its height is initially 11 pixels.

I want users to be able to double click on it when there are more status messages than what can fit within the default height for it to grow. If you double-click on it or remove the mouse from the field, it will shrink again.

I managed to get this to work exactly the way I want it, but it seems to me that one could write this more elegantly:

<script type="text/javascript">
    $(document).ready(function() {
        $("#footer").dblclick(showStatusBar);
    });     
    function showStatusBar() {
        var footer = $("#footer");
        footer.unbind('dblclick', showStatusBar);
        footer.animate({ height: "100px" }, 200);
        footer.dblclick(hideStatusBar);
        footer.bind('mouseleave', hideStatusBar);
    }

    function hideStatusBar() {
        var footer = $("#footer");
        footer.unbind('mouseleave', hideStatusBar);
        footer.unbind('dblclick', hideStatusBar);
        footer.animate({ height: "11px" }, 200);            
        footer.dblclick(showStatusBar);
    }
</script> 

      

I played around with the toggle event but couldn't get it to work.

+1


source to share


1 answer


You can create one function that acts as a toggle function. Something like that:

// NOTE: Untested!
function statusBarToggle() {
    /* Starts as hidden. */
    if(this.isHidden == undefined)
        this.isHidden = true;

    this.isHidden = !this.isHidden;

    var newHeight = this.isHidden ? 11 : 200;

    $(this)
        .stop()
        .animate({ height: newHeight + 'px' }, 200);

    /* When mouse leaves open status bar, close it. */
    if(this.isHidden)
        $(this).unbind('mouseleave', statusBarToggle);
    else
        $(this).bind('mouseleave', statusBarToggle);
}

$(document).ready(function() {
    // ...
    $('#footer').dblclick(statusBarToggle);
}

      



This gives the status bar the ishidden property and uses it to check if we are showing or hiding the status bar. This feature also works with other elements if you need it.

(That you can bind many jQuery commands, as I did above with the "stop" and "animate" functions.)

+5


source







All Articles