tags:

views:

46

answers:

2

Hello All,

I'm trying to create function, that after clicking on button, will open my search box, and after clicking again on this same button it will close it.

I have build this:

 $("#searchbutton").click(function(){
      $("#searchBox").animate({top: '0px'}, 500),

        $(this).click(function(){
        $("#searchBox").animate({top: '-47px'}, 500)
            });
        });

It works fine but only first time after i click on it. Then if I'll click on it again to re-open without refreshing the page button will automatically hide.

Why is it happening?

Thank you for your help in advance

Dom

+1  A: 

Your problem is that you never unbind the first click handler.

The best solution is to use the toggle handler, like this:

$("#searchbutton").toggle(
    function () { $("#searchBox").animate({top: '0px'}, 500); }, 
    function () { $("#searchBox").animate({top: '-47px'}, 500); }
);
SLaks
+1  A: 

Each time you're clicking on that you're adding another click event handler. You're not removing any. You could do this:

$("#searchbutton").click(show_search);

function show_search() {
  $("#searchBox").animate({top: '0px'}, 500)});
  $("#searchbutton").unbind("click", show_search).click(hide_search);
}

function hide_search() {
  $("#searchBox").animate({top: '-47px'}, 500)});
  $("#searchbutton").unbind("click", hide_search).click(show_search);
}

but adding/removing event handlers is kinda ugly. Luckily, there's an easier solution for this:

$("#searchbutton").click(function() {
  $("#searchbutton").slideToggle();
});
cletus