Reputation: 33
How do I optimize the code below? In less lines.
jQuery(document).ready(function(){
jQuery(".a1").hide();
jQuery(".a").click(function(){
jQuery(".a1").toggle();
});
jQuery(document).ready(function(){
jQuery(".b1").hide();
jQuery(".b").click(function(){
jQuery(".b1").toggle();
});
...
...
Edit. Add my Html code.
<ul class="bg">
<li class="a">Text</li>
<li class="a1"><a href="#">Text</a></li>
<li class="a1"><a href="#">Text</a></li>
</ul>
<ul class="bg">
<li class="b">Text</li>
<li class="b1"><a href="#">Text</a></li>
<li class="b1"><a href="#">Text</a></li>
</ul>
Thanks for answers.
Upvotes: 2
Views: 69
Reputation: 28513
Try this : You can make use of siblings()
to toggle li
s
$(function(){
$('.bg').find('li:first').siblings('li').hide();
$('.bg').find('li:first').click(function(){
$(this).siblings('li').toggle();
});
});
Upvotes: 1
Reputation: 428
You can do something like this:
<script>
$(function(){
$('ul.bg li:first').siblings().hide();
$('ul.bg li:first').on("click", function(){
$(this).siblings().toggle();
})
})
</script>
Try this and let me know if that helps you
Upvotes: 0
Reputation: 6031
use below code
jQuery(document).ready(function(){
jQuery(".bg").find('li:not(:first)').hide(); // hide all li inside .bg expat expat first.
jQuery(".bg").find('li:first').click(function(){ // click event on first li
$(this).nextAll('li').toggle(); // toggle other li expat first
});
});
Upvotes: 1
Reputation: 7878
You can try something like this:
jQuery(document).ready(function () {
jQuery(".bg").find('li:has(a)').hide(); //hide all list-elements
//containing an anchor element
jQuery(".bg > li:first-child").click(function () { //trigger click
// on the first list-element
$(this).siblings('li').toggle(); //toggle all other list-elements
});
});
It depends strongly on your provided html-markup, as it checks if there are a
-tags inside the list-elements, which should be shown on click. But you can expand your existing markup with no need to change something or add additional data to it.
Reference
Upvotes: 0
Reputation: 995
There's no need for more than one jQuery(document).ready(function() {
call.
jQuery(document).ready(function() {
jQuery(".a1, .b1").hide();
jQuery(".a").click(function() {
jQuery(".a1").toggle();
});
jQuery(".b").click(function() {
jQuery(".b1").toggle();
});
});
Upvotes: 0