There are number of examples for add and remove in jquery. But my code is bit different to examples. when i click add it show second and if i click again on add i want show third as well as when i click remove hide the third also until five. Here is my code
CSS
#second {
display: none;
}
#third {
display: none;
}
#forth {
display: none;
}
#fifth {
display: none;
}
HTML
<div id="header">
<a href="#" id="add1">add</a> - <a href="#" id="remove">remove</a>
<div id="first"><a href="#">first</a></div>
<div id="second"><a href="#">second</a></div>
<div id="third"><a href="#">third</a></div>
<div id="forth"><a href="#">forth</a></div>
<div id="fifth"><a href="#">fifth</a></div>
</div>`
JavaScript
$(document).ready(
function() {
$("#add1").click(function() {
$("#second").show();
});
$("#remove").click(function() {
$("#second").hide();
});
});
HERE IS CODE JSfiddle
Here is an approach you can use. First, add a class to all elements that you want to show / hide. In this case I used class toggle
:
<div id="header">
<a href="#" id="add1">add</a> - <a href="#" id="remove">remove</a>
<div id="first" class="toggle"><a href="#">first</a></div>
<div id="second" class="toggle"><a href="#">second</a></div>
<div id="third" class="toggle"><a href="#">third</a></div>
<div id="forth" class="toggle"><a href="#">forth</a></div>
<div id="fifth" class="toggle"><a href="#">fifth</a></div>
</div>
Then when you are adding an element, use function first
to find first not visible element with class toggle
and show it. When you want to remove element, use function last
to find last not visible element and hide it:
$(document).ready(function() {
// when add is clicked, show first not visible element with class 'toggle'
$("#add1").click(function() {
$('.toggle:not(:visible)').first().show();
});
// when remove is clicked, hide last visible element with class 'toggle'
$("#remove").click(function() {
$('.toggle:visible').last().hide();
});
});
Here is updated JSFiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.