Using jQuery slideToggle in a large list of individual elements

I have a large nested list that I am trying to animate using jQuery slideToggle. I want separate nested lists (id = "Nested" + counters) to be animated separately, so that the user can switch the list to show / hide without affecting the rest. The animation will be called by the corresponding trigger_Nested link (+ counter).

However, in the end there will be about 75 or so nested lists, and I do not want to separately indicate each pair of anchors and lists.

I feel that there is probably a very simple way to do this dynamically using a counter, but I'm a bit new to Javascript, so I can't figure it out. The Js that I have includes all the lists at the same time, which I don't want.

Any help is appreciated, thanks!

<head> <script src="jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $("ul[id|=Nested]").hide(); $("a[id|=trigger_Nested]").click(function() { $("ul[id|=Nested]").slideToggle("fast"); return false; }); }); </script> </head> <body> <ul id='TopLevel-List'> <li><a href=# id='trigger_Nested-0'>Top Level 1</a> <ul id='Nested-0' > <li><a href=#>Item 1</li> <li><a href=#>Item 2</li> </ul> </li> <li><a href=# id='trigger_Nested-1'>Top Level 2</a> <ul id='Nested-1'> <li><a href=#>Item 3</a></li> <li><a href=#>Item 4</a></li> <li><a href=#>Item 5</a></li> </ul> </li> </ul> </body> 
+4
source share
2 answers

You can change your selector in the .click() handler to use this and find the <ul> relative, for example:

 $(function(){ $("ul[id|=Nested]").hide(); $("a[id|=trigger_Nested]").click(function() { $(this).siblings("ul").slideToggle("fast"); return false; }); }); 

Here you can see a demo , it comes from the element you clicked (then <a> ), and finds it .siblings() , which correspond to the selector (in this case <ul> ), and slideToggle is the only one.

+1
source

What about a two-level indented list?

 <ul id="TopLevel-List"> <li><a href=# id="trigger_Nested-0">Top Level 1</a> <ul id='Nested-0' > <li><a href=# id='trigger_Nested-1'>Top Level 2</a> <ul id-'Nested-1'> <li><a href='#'>Item 1</a></li> <li><a href='#'>Item 2</a></li> <li><a href='#'>Item 3</a></li> </ul> <ul id-'Nested-1'> <li><a href='#'>Item 1</a></li> <li><a href='#'>Item 2</a></li> <li><a href='#'>Item 3</a></li> </ul> </li> </ul> </li> <li><a href=# id='trigger_Nested-1'>Top Level 2</a> <ul id='Nested-0' > <li><a href=# id='trigger_Nested-1'>Top Level 2</a> <ul id-'Nested-1'> <li><a href='#'>Item 1</a></li> <li><a href='#'>Item 2</a></li> <li><a href='#'>Item 3</a></li> </ul> <ul id-'Nested-1'> <li><a href='#'>Item 1</a></li> <li><a href='#'>Item 2</a></li> <li><a href='#'>Item 3</a></li> </ul> </li> </ul> </li> </ul> 
0
source

Source: https://habr.com/ru/post/1313344/


All Articles