0

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.

Duggy G
  • 465
  • 3
  • 12
  • 27

1 Answers1

1

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');
}
});
web hobbit
  • 501
  • 4
  • 17
  • Thankyou for the reply, tried this but still can't get it to work... you say give it an ID, give what an ID? – Duggy G Sep 18 '14 at 19:38
  • oooh , sorry i forgot to explain very well, my idea is this : you can give it any id you want to work with it in ( if(evt.target.id == "toggle-search") ). – web hobbit Sep 19 '14 at 09:35
  • This is nearly correct, The toggle content is closing when I click anywhere on the page apart from the toggle content which is what I want but now if I click anywhere on the page it opens and closes the toggle area? Thankyou for your help. – Duggy G Sep 19 '14 at 14:11
  • I updated the code, but i didn't test it i hope it work if it doesn't i well create an example for you . – web hobbit Sep 19 '14 at 16:44
  • I have just added a form and links into the toggle-search div and it's still closing the div if I click inside the toggle div. It's fine with basic text but not other elements. Any ideas? – Duggy G Sep 20 '14 at 13:32
  • I've edited the code to show an unordered list with links. adding this list allows me to toggle within the togglesearch div which I do not want. – Duggy G Sep 23 '14 at 13:30
  • i cannot figure it out without the code source can you post please the new chanages that you made – web hobbit Sep 23 '14 at 14:53