0

I've a tree menu. The last <li> element from this menu contains an <a> element.

I'm using the jQuery toggle() method.

I know that toggle() contains an e.preventDefault() by default.

What I wanna do is give back the click event to the <a> element.

Could you pls help?

HTML:

<ul class="menu">
    <li>
        Item1
        <ul style="display: none">
            <li>
                subItem1
                <ul style="display: none">
                    <li>
                        <a href="http://www.google.com">Google</a>
                    </li>
                    <li>
                        <a href="http://www.yahoo.com">Yahoo</a>
                    </li>
                    <li>
                        <a href="http://www.facebook.com">Facebook</a>
                    </li>     
                </ul>
            </li>
        </ul>
    </li>
</ul>

Javascript:

$(".menu li").toggle(
    function() {
        $(this).children().slideDown();
    },

    function() {
        $(this).children().slideUp(); 
    }
);

Please check this fiddle: http://jsfiddle.net/fzy48/

Rodrigo Abib
  • 83
  • 1
  • 2
  • 14
  • Have you tried what this question suggests? ... http://stackoverflow.com/questions/1551389/how-to-enable-default-after-event-preventdefault – Jodes Mar 13 '13 at 10:10

2 Answers2

1

You were missing some closing tags.

See the updated fiddle.

$(".menu li").on('click', function(e) {
    e.stopPropagation();
    $(this).children('ul').slideToggle();
});

Using the on() method you have more control over your functionality. What you need is the stopPropagation() method: it prevents the click event from bubbling up the dom tree to a parent li which would slide-toggle it.

Also by filtering the children of the clicked li to only ul's you are more explicit in what you want to toggle.

Flauwekeul
  • 869
  • 7
  • 24
0

An alternative version to Flauwekeul's one, using .on() event delegation:

$('.menu').on('click', 'li', function(event){
    if (event.target != this) {
     return;//dont want bubbled up events
    }
    $(event.target).children('ul').slideToggle();
});

See it in http://jsfiddle.net/fzy48/5/

The advantage of using event delegation is we just attach one event handler(in the parent .menu element), instead of one event handler per li element.

Nelson
  • 49,283
  • 8
  • 68
  • 81