0

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

2 Answers 2

1

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); }
);
Sign up to request clarification or add additional context in comments.

Comments

1

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.