views:

47

answers:

1

Hi, I've a div in a absolute position with a default "top" value set to "-200px". When i click on the div the "top" value is updated to "0". In this way I see the entire Div.

This is the js:

$(document).ready(function(){
  $("#search_bar").click(function () {
    $(this).css("top","0");
  });
});

Is there a way to achieve this result but with an animation? For example, a slide down effect?

Also, when i click another time to the div I'd like that the "top" value will be restored to "-200px".

+2  A: 

Of course. Use the .animate() method. And instead of the click event, use toggle which accepts two functions for before/after.

Live Example: http://jsfiddle.net/a86tm/1/

$(document).ready(function(){

  $("#search_bar").toggle(  // toggle() takes 2 functions
      function () {
          $(this).animate({top: 0}, 500);  // Use animate() to animate the transition.
      },                                   // The 500 argument is the duration.
      function() {
          $(this).animate({top: -200}, 500);
      }
  );

});​

jQuery docs:

patrick dw
This code doesn't work with Google Chrome!The console give me this error:Uncaught SyntaxError: Unexpected token ILLEGAL at line 6 which is the last line of the script.
Pennywise83
@Pennywise - I'm guessing you copied the code from the jsFiddle? If so, there are some invisible (illegal) characters that get copied with it. Either delete some white space after the end of the code, or copy and paste the code from above.
patrick dw