I want to open and close these lists with a single javascript function.
I don't want to write more than one javascript function for each list.
How can I do? The above are my codes
$(document).ready(function(){
$(".close").click(function(){
$(".content").toggle("slow");
});
});
.close {padding:0 5px;margin-left:10px;cursor:pointer;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
Contents
<span class="close">hide</span>
<div class="content">
<ul>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
</ul>
</div>
</div>
<div>
Contents
<span class="close">hide</span>
<div class="content">
<ul>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
</ul>
</div>
</div>
You can use jQuery
function next() to toggle on your element
which is next to the span
(hide)
In jQuery $(this)
refers to the element
we have clicked
on and then we get the next()
element which is your .content
class to toggle slow on that.
This way. You do have to write the code
again and again.
Live Demo:
$(document).ready(function() {
$(".close").click(function() {
$(this).next().toggle("slow");
});
});
.close {
padding: 0 5px;
margin-left: 10px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
Contents<span class="close">hide</span>
<div class="content">
<ul>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
</ul>
</div>
</div>
<div>
Contents<span class="close">hide</span>
<div class="content">
<ul>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
<li><a href="">link</a></li>
</ul>
</div>
</div>