Reputation: 477
I'm struggling with a div that I'm toggling, everything I have is working fine when I click the link with id of #togglesearch but what I want is to be able to close the visible div that has been toggled when I click anywhere on the page apart from the div that has been toggled.
This is what I have at the moment:
<script type="text/javascript">
jQuery(document).ready(function($){
jQuery('#togglesearch').click(function() {
jQuery('.toggle-search').slideToggle('fast');
return false;
});
});
</script>
and the html is simple:
<a href="#" id="togglesearch">Slide Toggle</a>
<div class="toggle-search" style="display:none;">
<ul>
<li><a href="#">Link One</a></li>
<li><a href="#">Link Two</a></li>
<li><a href="#">Link Three</a></li>
</ul>
</div><!-- end toggle content -->
The .toggle-search is the div that is being toggled but I do not want it to close if I click on that div, just everywhere else on the page.
Thankyou.
Upvotes: 0
Views: 202
Reputation: 501
Give it and id = 'toggle-search' and try this code.
$('body').click(function(evt){
if(evt.target.id == "toggle-search") {
return;
}else if(evt.target.id == "togglesearch") {
// toggle here
jQuery('.toggle-search').slideToggle('fast');
} else {
jQuery('.toggle-search').slideUp('fast');
}
});
Upvotes: 1