javascript - JQuery navigation tree open/close on click -


i'm not jquery or javascript expert , have little problem website navigation. navigation looks typical windows resource management navigation e.g:

title     subtitle     subtitle         subsubtile     subtitle title     subtitle 

i want works same typical windows resource management navigation, when click title subtitles able see , when reclick title it's hide clicked title subtitles.

with following code able open titles, don't have idea how close them.

$( document ).ready(function() {     $('#navigation').click(function() {         $('#navigation ul li:hover').children('#navigation ul li ul').slidedown(400);     }); }) 

there convenient shorthand in jquery: .slidetoggle()

the selected element displayed if it's not, , vica-versa.

the other important part is, can use $(this) in event handler. element event handled on.

also .children() tree traversal function. means it's results selected relative selected elements called on. $('#example').children('a') select links directly under example element, no $('#example').children('#example a') needed.

i have wrapped code you:

$(document).ready(function() {     $('#navigation ul li').click(function(e) {         e.stoppropagation();         $(this).children('ul').slidetoggle(400);     }); }); 

or if prefer have 1 event handler , bubbling:

$(function() {     $('#navigation').on('click', 'li', function(e) {         e.stoppropagation();         $(this).children('ul').slidetoggle(400);     }); }); 

of course these 2 work if <ul> toggle direct child of <li> fire click event on.

edit:

as @thebreiflabb mentioned in comments, because of event bubbling click event fired on every parent of clicked element default.

if of parents match selector, same event handler called on them.

e.stoppropagation() tells, event handled here , not need fire on parent elements.

to see difference click on "subitem 2" under "item 4" in both of these fiddles:

with stopping propagation.

without stopping propagation.

as can see, without stoppropagation() "item 4" closes.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -