Question

I have this bit of JQuery to hide and show LIs under a UL when it's clicked, and it works. However, when I click one of the links under a UL it closes and I would like it to stay open.

<script type="text/javascript">
$(function () {
    $('.headlink').click(function() {
        $(this).children('ul').slideToggle();
    });    
    $('.headlink').click(function(event) {
        event.stopPropagation();
    });
});
</script>

This is the UL.

<ul class="arclist">
    <li class="headlink">
    <h2>+ Top Link</h2>
        <ul class="transcriptfile" style="display:none;">';
    <a href="transcripts/filename"><li>
    <p>Clickable Link</p></li></a>
        </ul>
</ul>

If populates the ULs and LIs from a bit of PHP code, but I took it out for ease of reading. Like I said, everything works, I get multiple ULs and multiple LIs and the clickable links all work, but it just toggles the slide and hides it again after clicking one of the Clickable Links and I don't want it to.

Was it helpful?

Solution

You could use .stopPropagation() on the folded out menu to prevent it from toggle on click.

http://jsfiddle.net/pVQsv/

$(function () {
    $('.headlink').click(function () {
        $('ul', this).slideToggle();
    });
    $('.headlink ul').click(function(e) {
        e.stopPropagation();
    });
});

OTHER TIPS

You can bind the handler on the h2 element like this:

$('.headlink h2').click(function() {
    $(this).next('ul').slideToggle();
});

Check This Demo

I tried using e.stopPropagation(); in very different ways, but it didn't work for me :(

So the solution I found was this:

$(function () {
    $('.headlink').click(function() {
        $('.headlink ul').slideToggle();
    });

    $("headlink ul a").click(function() {
        $(".headlink ul").stop();
    });
});

Maybe it's not the most conventional way to do it, but it works too :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top