raq
raq

Reputation: 175

on click toggle ul - on click elsewhere hide ul

hey all - my second day of attempting jquery on a task at work, and am a bit stuck.

i've got an unordered list of links.. inside an unordered list of links

on clicking an <li class="headlink">, I would like the <li class="headlink"> 's child <ul> to become visible.

on clicking away (anywhere on the document), I would like the child <ul> to dissapear.

By default the child <ul> is set to hidden in the stylesheet.

html

<ul id="cssdropdown">
    <li><a href="#">A</a></li>
    <li class="headlink">
        <a href="#">B</a>
        <ul>
            <li><a href="#">1</a></li>
            <li><a href="#">2</a></li>
        </ul>
    </li>
    <li><a href="#">C</a></li>
</ul>

jquery

<script type="text/javascript">

    $(document).ready(function(){
        $('#cssdropdown li.headlink').click(
            function() { $('ul', this).toggle("slow"); });
    });


    $(document).ready(function(){
        $('body').click(function() { 
            $('li ul:visible').hide("slow") } ) } );

</script>

Problem - when I click on a <li class="headlink">, I get the yoyo effect, where the child UL is displayed - and then hides itself.

any advise much appreciated.

Upvotes: 2

Views: 8572

Answers (2)

Seb
Seb

Reputation: 25147

You should prevent the event to propagate back to the body:

$(document).ready(function(){
    $('#cssdropdown li.headlink').click(function(event) {
      $('ul', this).toggle("slow");
      event.stopPropagation();
    });
});

And to hide current open items:

$(document).ready(function(){
    $('#cssdropdown li.headlink').click(function(event) {
      $(this).siblings(".headlink").hide("slow");
      $('ul', this).toggle("slow");
      event.stopPropagation();
    });
});

Upvotes: 4

cgp
cgp

Reputation: 41381

This will fix the issue for the "yo-yo" effect: (cancel propagation)

$(document).ready(function(){
    $('#cssdropdown li.headlink').click(
        function(event) { 
          $('ul', this).toggle("slow"); 
          event.stopPropagation()
      });
});

Upvotes: 1

Related Questions