I created a quick script that allows a dropdown menu in my header. However I am trying to make it so that when they are open, if someone clicks somewhere else in the document they will automatically close. Here is the code I have so far: j(document).ready(function(){ /*Header Dropdowns*/ var cartLink = j('#cart-header'); var cartMenu = j('#cart-dropdown'); var searchLink = j('#search-header-link'); var searchMenu = j('#search-header-menu'); var isCartOpen = false; var isSearchOpen = false; var openSearch = (function(){ searchMenu.slideDown( "fast", function(){ searchMenu.css("display", "block"); }); isSearchOpen = true; }); var closeSearch = (function(){ searchMenu.slideUp( "fast", function(){ searchMenu.css("display", "none"); }); isSearchOpen = false; }); var openCart = (function(){ cartMenu.slideDown( "fast", function(){ cartMenu.css("display", "block"); }); isCartOpen = true; }); var closeCart =(function(){ cartMenu.slideUp( "fast", function(){ cartMenu.css("display", "none"); }); isCartOpen = false; }); cartLink.click(function() { if(isSearchOpen == true){ closeSearch(); } if(isCartOpen == false){ openCart(); } else { closeCart(); } }); searchLink.click(function() { if(isCartOpen == true){ closeCart(); } if(isSearchOpen == false){ openSearch(); } else { closeSearch(); } }); }); Code (JavaScript):
... and you are using .js to do CSS' job why exactly? Just TRYING to make the page harder to use with js for nothing?
I would be happy to take your advice, but as of right now it is the only way I know how to accomplish this.
I'm guessing wildly since you didn't provide markup or style, but the answer is :target -- at least for modern browsers. Legacy IE (9 and lower) doesn't know :target, but we can add a polyfill to fix that if you REALLY care. For example: http://www.cutcodedown.com/for_others/Borduhh/template.html As with all my examples the directory: http://www.cutcodedown.com/for_others/Borduhh/ is wide open. For now the demo just hides/shows the dropdown using overflow:hidden to chop it off, but since in modern browsers it's completely CSS controlled, you could add any CSS animation you wanted to there. (though for slide-in type tricks you may have to use an extra wrapping DIV in the markup) The polyfill isn't the greatest, I just slapped it together quick and it just adds the class "target' when a anchor is followed to a index of the page. Hope this helps.
You could just look for any clicks in the body and check to see if either are open. Something like: var isCartOpen = false; $('body').click(function() { if(isCartOpen) { // close the menu } }); Code (markup):