I have html like
<ul>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
CSS:
li {display:none;}
li.dropdown {display:block;}
When we click on li.dropdown
, all the <li>
without classes, from the current to the next li.dropdown
, should bee visible. And opposite action when we click it again - hide <li>
without class dropdown
.
How do I do this?
I have html like
<ul>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li class="dropdown">text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
CSS:
li {display:none;}
li.dropdown {display:block;}
When we click on li.dropdown
, all the <li>
without classes, from the current to the next li.dropdown
, should bee visible. And opposite action when we click it again - hide <li>
without class dropdown
.
How do I do this?
Share Improve this question edited Jun 3, 2012 at 17:47 Gilles 'SO- stop being evil' 108k38 gold badges215 silver badges260 bronze badges asked May 15, 2011 at 21:08 JamesJames 43.6k54 gold badges137 silver badges163 bronze badges4 Answers
Reset to default 7The correct way to do this would be with submenus, so:
<ul>
<li class="dropdown">text
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
</li>
etc...
</ul>
You can then do
$('li.dropdown').click(function() {
$(this).find('ul').slideToggle('slow');
});
Otherwise, you'll have to use nextUntil
:
$('li.dropdown').click(function() {
$(this).nextUntil('li.dropdown').slideToggle('slow');
});
This will have the disadvantage of hiding each of the nested li
elements individually, rather than as a block. Do the first if you can.
I would remend using a nested list structure lik this:
<ul>
<li class="dropdown">text
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
</li>
<li class="dropdown">text
<ul>
<li>text</li>
<li>text</li>
</ul>
</li>
</ul>
Creat a CSS like this:
li.dropdown ul {
display : none;
}
And then only show/hide the nested unordered lists:
$('li.dropdown').click(function() {
$(this).children('ul').toggle();
});
If you have the item in $dropdown variable then you can use this:
$dropdown.next( "li:not(.dropdown)" ).hide();
That will hide all not .dropdowns;
To do this until the next .dropdown you will need to use:
$dropdown.next("li").each(...);
$("li.dropdown").click(function() {
$(this).nextUntil(".dropdown").toggle();
});
Fiddle