tags:

views:

46

answers:

3

I have the following code:

<ul class="cssdropdown">
    <li class="headlink">RANGE
        <ul class="innerDrop">
            <li>Range Child</li>
        <ul>
    <li>
    <li class="headlink">HOME
        <ul class="innerDrop">
            <li>Home Child</li>
        <ul>
    <li>
</ul>

I'm trying to toggle the <ul class="innerDrop" with some jQuery. And I need to do it by adding a class the hide class which has display:none

It hides fine, but when I click on the HOME or RANGE it opens both inner <li> when I just want the one to open.

Here is my jQuery:

$(document).ready(function(){

        $('li.headlink ul').addClass('hide');
        $('#header').append('<div class=\"showpersonal\" onclick=\"toggleMenu()\"></div>');
        $('#header').append('<div class=\"showbusiness\" onclick=\"toggleMenu()\"></div>');
    });
    function toggleMenu() {
        $('li.headlink ul').toggleClass('hide', this);

    }
+2  A: 

Your jquery

$('li.headlink ul').toggleClass('hide', this);

will find all ul lists inside any li.headlink anywhere in the DOM. Change it to

$(this).find('li.headlink ul').toggleClass('hide');

and it should work as expected, as long as this refers to the correct node. To be sure of that, you can add this as a parameter to toggleMenu in the event trigger and edit the toggleMenu function accordingly.

// Event trigger
onclick="toggleMenu(this);"

// Event handler
function toggleMenu(node) {
    $(node).find('li.headlink ul').toggleClass('hide');
}

Then it's arguable if the click event is the best way to open a submenu. The common way to do it is - IMHO - to open the submenu on hovering. But that's, of course, subjective.

nikc
+1  A: 

Here's an example

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">

    $(document).ready(function(){

        $('li.headlink ul').addClass('hide');
        $('li.headlink').click(function(){
            $(this).children('ul').toggleClass('hide');
        });

    });

</script>
<style type="text/css">
    .hide{display:none;}
</style>
</head>
<body>
<ul class="cssdropdown">
    <li class="headlink">RANGE
        <ul class="innerDrop">
            <li>Range Child</li>
        </ul>
    </li>
    <li class="headlink">HOME
        <ul class="innerDrop">
            <li>Home Child</li>
        </ul>
    </li>
</ul>
</body>
</html>
Jonathan
+2  A: 

you question was answered by nikc, just a hint from my side jQuery allows you to add a click handler on creating an element in a way like:

$('<div/>', {
   class:    'showpersonal',
   click:    function(e){
      $(this).find('li.headlink ul').toggleClass('hide');
   }
}).appendTo('#header');

Kind Regards

--Andy

jAndy
+1 For elegance and also for not just answering the question, as I did, but providing alternative approach.
nikc