Reputation: 25
I have an ordered list which when each item is clicked it will toggle show/hide a corresponding div however, I am really unsure of how to do this in a mannor that works best. I know how to do it if I give each item an id or class but I'm sure there is a better way than writing lines and lines of code if it was a big list.
Basically what I have is this:
<ol>
<li id="no1">Money Savings</li>
<p id="reasonText">
Some text....
</p>
<li>Stable Fares</li>
<p id="reasonText2">
Some text...</p>
<li>Reason 3</li>
<p id="reasonText3">Some text...</p>
etc....
JQuery:
$("#no1").click(function(){
$("#reasonText").slideToggle('slow')
Is there a better way to iterate through each li and show or hide the div that follows other than basically repeating what I have in my jquery?
Upvotes: 0
Views: 6033
Reputation: 2239
Using all classes instead of ids would be a better way of doing this:
<ol>
<li class="reason">Money Savings <p class="reasonText">Some text....</p></li>
<li class="reason">Stable Fares <p class="reasonText">Some text...</p></li>
<li class="reason">Reason 3 <p class="reasonText">Some text...</p></li>
</ol>
The jQuery would then be as follows:
$('.reasonText').hide(); //hide all the reason text
$('.reason').on('click', function() {
$(this).children('.reasonText').slideToggle('slow');
});
I moved the <p>
tags into the <li>
tags because only <li>
tags can appear in <ol>
tags. If you want to keep your markup with the exception of changing ids to classes.
<ol>
<li class="reason">Money Savings</li>
<p class="reasonText">Some text....</p>
<li class="reason">Stable Fares</li>
<p class="reasonText">Some text...</p>
<li class="reason">Reason 3</li>
<p class="reasonText">Some text...</p>
</ol>
The jQuery would be as follows:
$('.reasonText').hide(); //hide all the reason text
$('.reason').on('click', function() {
$(this).next('.reasonText').slideToggle('slow');
});
Upvotes: 1