Search code examples
javascripthtmlexpandable

Collapsing and opening a div via a close button


I am trying to build using javascript a panel that expands out of the right side of the browser window, in which it will hold information. I have managed to get the div to expand on click but I need it to expand on hover, and also close with an x in the corner to return to its original state.

http://jsfiddle.net/8zGp9/

I hope this is clear, my Fiddle is above.

<div> </div>

Solution

  • Use hover. The first function will take action on hover and the second when you hover out. See example

    $("#slidingpanel").hover(function(e){
        $(this).animate({
            width: 200
        },100);
    },function(e){
        $(this).animate({
            width: 30
        },100);
    });
    

    If you want to close your div on click only you can try this:

    $("#slidingpanel").hover(function(e){
        $(this).animate({
            width: 200
        },100);
        $("#closeButton").css("display", "inline-block");    
    });
    
    $("#closeButton").click(function(){
        $("#slidingpanel").animate({
            width: 30
        },100);
        $(this).css("display", "none").delay(200);
    });
    

    Working example

    I located the X outside because if it's inside once you clicked it and moved the mouse, the hover will be fired again.