Pete
Pete

Reputation: 87

jQuery animation: Partly reveal div (like opening a drawer)

I'm comfortable using jQuery to show() a div or make it slideDown() etc but I am struggling to achieve an a particular effect.

On hover over a parent div I'm looking for the child to slide down, as if using

$('.divClass').toggle("slide", { direction: "up" }, 500); 

from the jQuery UI Library. (See in a fiddle).

However, I would like to be able to only reveal a small part of the child div on hover and then slide the rest into view on click.

Setting the css height property of the child div I have rather messily got this far (fiddle)...

$('.hoverDiv').hover(
 function () {
     $('.child').animate({
         height: '25px'
     }, 200);
 });

$('.hoverDiv').click(
 function () {
     var cont = $('.child');
     cont.animate({
         height: '0px'
     }, 200, function () {
         cont.css({
             height: 'auto',
             display: 'none'
         });
         cont.slideDown(200);
     });
 });

But I've lost the "sliding drawer" look. Any ideas how to get it back?

Upvotes: 3

Views: 1869

Answers (2)

prograhammer
prograhammer

Reputation: 20590

Try switching your hover to a mouseenter/mouseleave and adjust your click a bit (I used scrollHeight for the height):

http://jsfiddle.net/nTn38/4/

Here's the modified JS:

$('.hoverDiv').mouseenter(function () {
      $(this).find('.content').animate({
          height: '25px'
      }, 200);
}).mouseleave(function () {
      $(this).find('.content').animate({
          height: '0px'
      }, 200);
}).click(function () {
      $(this).find('.content').animate({
          height: $(this).find('.content')[0].scrollHeight
      }, 200);
});

Upvotes: 1

James Montagne
James Montagne

Reputation: 78650

If I understand you correctly, I think something like this will work:

http://jsfiddle.net/Y4heX/3/

<div class="hoverDiv">Hover Me
    <div class="wrapper">
        <div class="content">see a tiny bit of content. Click to see the rest
            <br>sdf
            <br>asdf</div>
    </div>
</div>
$('.hoverDiv').each(function () {
    var $content = $(this).find('.content').show();

    $content.css("margin-top", -1 * $content.height());
}).hover(function () {
    var $content = $(this).find('.content');

    $content.animate({
        "margin-top": -1 * ($content.height() - 25)
    }, 200);
}, function () {
    var $content = $(this).find('.content');

    $content.animate({
        "margin-top": -1 * $content.height()
    }, 100);
});


$('.hoverDiv').click(function () {
    var cont = $(this).find('.content');
    cont.animate({
        "margin-top" : 0
    }, 200);
});

I added a wrapper with overflow: hidden and use margin-top to hide some portion of the div above the wrapper.

Upvotes: 0

Related Questions