views:

375

answers:

2

Hi

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

I want to allow users to double click it when there are more status messages than what can fit within the default hight, make it grow. If they double click it again or move the mouse away from the box, it should shrink again.

I am completely new to javascript and jquery, so bare with me. I manage to get this working exactly as I want, but it seems to me that it should be possible to 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 was unable to get it working. Input will be much appreciated.

Best regards, Egil.

+5  A: 

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

// 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 an "isHidden" property, and uses it to check if we are showing or hiding the status bar. This function also works with other elements if you need it to.

(That that you can chain many jQuery commands, as I did once above with the 'stop' and 'animate' functions.)

strager
A: 

Hi strager

Cool, thank you. I was not aware that you could add new properties to objects.

Question: Why do you use the .stop() method in the animation?

Egil Hansen
Using .stop() prevents the new animation queueing - if you clicked furiously on the status bar you would have lined up a huge queue of pop-up - pop-down animations - not quite the result you want! Stopping it before hand prevents this.
Simon
@Egil: This is not a forum, comment strager's answer if you have questions regarding it.
Chei
Simon: makes sense, thanks.Chei: sorry, my bad, still new to this site and its ways.
Egil Hansen