February 26, 201214 yr I know how to create a drop down menu with :hover in CSS but what I want to know is how I can have a drop down menu so that when you click on the link/button it comes down, and stays down even if you move the mouse off it, then when you click anywhere on the screen it disappears. An example would be Facebook, they use this on their 'down arrow' next to 'Home' in the top right corner. I've tried using the onclick event with javascript, and I'm sure this must be part of the process (if not please correct), but I can't find a solution to being able to click anywhere on the screen to remove the menu.
February 27, 201214 yr Why not share the solution so others can learn for when they search this stuff
February 27, 201214 yr Author I used the jQuery library to work this out. <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" > $(document).ready(function(){ $("html").click(function(){ $("#div").hide(); }); $("#buttonDiv").click(function(){ $("#div").slideDown(200); }); $('#div').click(function(){ event.stopPropagation(); }); }); </script> <style type="text/css"> body { } button { margin: 0; padding: 0; } #buttonDiv { border: 1px solid black; height: 20px; width: 100px; } #buttonDiv:hover { cursor: pointer; } #div { border: 1px solid black; width: 98px; height: 100px; top: 100px; position: relative; } </style> </head> <body> <button type="button" id="buttonDiv">Show</button> <div id="div"> <a href="#">something</a> </div> </body> </html> </script>
February 27, 201214 yr Author You'll need some absolute positioning on the dropdown so it overlaps content Yeah I found that out when I implemented it into my site, I needed to use absolute positioning and a z-index of 2 so that it would be on top of everything else. One thing I can't figure out... I used the 'html' element so that any click outside the div would hide it, but it doesn't work if I click inside an iFrame... any ideas?
February 27, 201214 yr Author An iframe is a completely separate document with its own DOM. is there no way of doing it then? that would really suck for me
Create an account or sign in to comment