I'm new to jQuery and need some help to show and hide a div on click. Basically I need to show a div (containing a small menu) once the user click on a link, and as soon as the user click on a link inside the div just shown. Or clicks outside the div I need to hide the div again.my HTML looks something like this (I'll exist in many places on the page).
<a class="menu" href="#">Menu</a>
<div class="menu-content" style="display: none; position: absolute; border: 1px solid black; background-color: White;padding: 5px;">
<div><a href="#">Menu option 1</a></div>
<div><a href="#">Menu option 2</a></div>
</div>
I also have a div that wraps the whole page that I thought I'd set another click-event on to hide the div (to catch clicks outside of the actual menu).
Is this the right approach for solving this and how do I then remove the handlers on the wrapper div etc, etc. What else should I think of to get this right (if it it's the right approach that is)?
Update: Based on the accepted answer below I added this to solve it
//Need to return false here, otherwise the event will bubble up and trigger the hide on body
$('.menu').click(function() { $('.menu-content').hide();$(this).next().show();return false; });
$('body, .menu-content a').click(function() { $('.menu-content').hide();});
$('.menu-content a').click(function() { alert($(this)); });
html:
<a class="menu" href="#">Menu</a>
<div class='a_menu' style="display: none; position: absolute; border: 1px solid black; background-color: White;padding: 5px;">
<div><a href="#">Menu option 1</a></div>
<div><a href="#">Menu option 2</a></div>
</div>
script:
$('.menu').click(function() { $(this).next('.a_menu').show(); });
$('body, .a_menu a').click(function() { $('.a_menu').hide(); });
I'd prolly replace the < A > tags with SPANS instead styled with 'cursor:pointer'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With