I came up with some very basic jQuery using a series of if-statements to show/hide some Divs on a page via an html select list. I would like to optimize this code in a couple ways if possible:
1) How Can I use less code to achieve the same result?
2) This is maybe a bit broad, but how can I optimize this code so that new Divs don't have to be manually typed out? In other words, make it so i don't have to specifically add $(block-x).hide() $(block-x).show() etc...
HTML:
<div class="container">
<form class="form">
<div class="form-group">
<label for="selectList">Filter Divs</label>
<select id="selectList" class="form-control">
<option value="1" id="lAll" selected="selected">Show All</option>
<option value="2" id="lOne">One</option>
<option value="3" id="lTwo">Two</option>
<option value="4" id="lThree">Three</option>
<option value="5" id="lFour">Four</option>
</select>
</div>
</form>
<div class="filterDiv">
<div id="block-1">
<h1> Div One</h1>
</div>
<div id="block-2">
<h1> Div Two</h1>
</div>
<div id="block-3">
<h1> Div Three</h1>
</div>
<div id="block-4">
<h1>Div Four</h1>
</div>
</div>
</div>
JAVASCRIPT:
$('#selectList').change(function() {
$('#block-1').hide();
$('#block-2').hide();
$('#block-3').hide();
$('#block-4').hide();
if ($('#lAll').is(':selected')) {
$('#block-1').fadeIn();
$('#block-2').fadeIn();
$('#block-3').fadeIn();
$('#block-4').fadeIn();
}
if ($('#lOne').is(':selected')) {
$('#block-1').fadeIn();
}
if ($('#lTwo').is(':selected')) {
$('#block-2').fadeIn();
}
if ($('#lThree').is(':selected')) {
$('#block-3').fadeIn();
}
if ($('#lFour').is(':selected')) {
$('#block-4').fadeIn();
}
});
Fiddle: http://ift.tt/1OL07eU
Thanks, Matt
Aucun commentaire:
Enregistrer un commentaire