Search code examples
jqueryhtmlslideslidetogglejquery-effects

Slide div/image out partially with JQuery


i'm facing a problem i cant solve on my own:

I got a div with a background image which i want to toggle slide up/down when the div is clicked. Problem is the image always slides up completely (100%) so it is gone. I want it to stay out 20% so you can click on it and it slides down 100% again.

I tried .animate() but it changes the aspect ratio of the picture, it wont slide out then.

I checked solutions like http://spoonfedproject.com/jquery/jquery-slide-with-minimum-height/ where divs slide in/out but it doesnt have the background picture...

Anyone got an idea? I would really appreciate it!

JS Fiddle: http://jsfiddle.net/JmLqp/105/

HTML Code

<div id="contact"></div>

CSS Code

#contact{
 width:162px;
 height:336px;
 background: url(http://s18.postimage.org/kl4b1rly1/bg_contact.png) no-repeat;
}

JS Code

$("#contact").click(function () {
  $(this).hide("slide", {direction: "up"}, 1000);
});

Solution

  • You were on the right track with animate():

    $("#contact").css('position', 'relative').click(function () {
        if($(this).offset().top == -250) {
             $(this).animate({'top': '0px'}, 1000);
        }
        else {
             $(this).animate({'top': '-250px'}, 1000);
        }
    });
    

    Note that you have to set the position to relative for yourself as above.

    Working Fiddle