Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndres Ramirez
18,094 PointsHide dropdown on body click...
I have a search box on my website, which slides out when the search button is clicked.
As of now, the only way of disappearing the search box, is by clicking on the search button as well. I would like this to disappear on any click of the body (outside the search box) as well. How can I do this?
Here is my JS code:
/-> start: SEARCH BUTTON DROPDOWN */ $('.search-button-main').click(function() { animationSpeed=250; if($(".search-button-main").hasClass("active")) { $('.search-dropdown-menu').animate({ height:'40px'},animationSpeed,function(){ $('.search-dropdown-menu').animate({ width:'0'},animationSpeed,function(){ $(".search-button-main").removeClass("active"); }); }); } else { $('.search-dropdown-menu').animate({ width:'350px'},animationSpeed,function() { $('.search-dropdown-menu').animate({ height:'450px'},animationSpeed,function() { $(".search-button-main").addClass("active"); $(".filterEvents").focus(); }); }); } }); / end. <-*/
1 Answer
Steven Parker
231,271 PointsWithout seeing the HTML this works on I can't be specific; but what comes to mind would be to establish a delegated handler on the document or window to allow you to respond to clicks elsewhere.
Since you're using jQuery, you might be able to use the ".on" method with the optional "selector" argument in setting this up.
Andres Ramirez
18,094 PointsAndres Ramirez
18,094 PointsHi Steven, thanks for your response. I figured it out. I have to add a body.click function function in the script. Cheers!
Steven Parker
231,271 PointsSteven Parker
231,271 PointsI was thinking document or window but body works too!
Glad I could help, and happy coding!