v4111
v4111

Reputation: 25

How do I modify this code to allow a different element to trigger the event?

HTML

<div id="sidebar">
<ul>
    <li>
        <h2>
            HEADER
        </h2>
        <ul>
            <li><a href="#">li3</a></li>
            <li><a href="#">li2</a></li>
            <li><a href="#">li3</a></li>
        </ul>
    </li>
</ul>
</div>

jQuery

$(document).ready(function () {
    $('li').click(function () {
        if ($('ul', this).is(":hidden")) {
            $('ul', this).slideDown("slow");
        }
        else {
            $('ul', this).slideUp("slow");
        }
    }
);
});

I only want slideUp(), slideDown() to be reached if the <h2> is clicked. Currently, both are called if any <li> is clicked.

How can I fix this?

Upvotes: 0

Views: 36

Answers (2)

Gustav Larsson
Gustav Larsson

Reputation: 8487

If you want it triggered when the h2 is clicked, shouldn't you do?

$(document).ready(function () {
    $('h2').click(function () {
        if ($('ul', this).is(":hidden")) {
            $('ul', this).slideDown("slow");
        }
        else {
            $('ul', this).slideUp("slow");
        }
    }
);
});

Upvotes: 0

alex
alex

Reputation: 490263

$(document).ready(function () {
    $('h2').click(function () {
        $(this).next('ul').slideToggle('slow');
    });
});

Upvotes: 2

Related Questions