javascript - Simplfly jQuery and HTML to show/hide divs on page -
i came basic jquery using series of if-statements show/hide divs on page via html select list. optimize code in couple ways if possible:
1) how can use less code achieve same result?
2) maybe bit broad, how can optimize code new divs don't have manually typed out? in other words, make don't have 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: https://jsfiddle.net/matts213/29ksshrr/5/
thanks, matt
change blocks have common class , can use value of select shorten code:
$('#selectlist').change(function() { var selected = parseint($('#selectlist').val()); var = (selected === 1) ? $('.container').children().fadein() : false; var showitem = (selected > 1) ? $('.container').children(':nth-child(' + (selected - 1) + ')').fadein().siblings().hide() : false; });
Comments
Post a Comment