Monday, 15 August 2011

javascript - filtering and sorting divs -



javascript - filtering and sorting divs -

i have been looking robust , simple way sort casestudies after couple of hours , search of stack overflow not find way filter casestudies way want.

basically give each casestudy 3 categories (year produced, type of project , name) using css classes, illustration markup this

<div class="name1 home 2013"></div> <div class="name2 work 2012"></div> <div class="name3 home 2012"></div> <div class="name4 charity 2012"></div> <div class="name5 home 2010"></div> <div class="name6 work 2007"></div>

then want have buttons can take category want sort casestudies by. like.

<div class="button" id="year">sort year</div> <div class="button" id="alpha">sort alphabetically</div> <div class="button" id="type">sort type</div>

this getting stuck. javascript function can create if click button "sort year" create mark looks this. eg sorting casestudies in divs casestudies of same year.

<div> <div class="name1 home 2013"></div> </div> <div> <div class="name2 work 2012"></div> <div class="name3 home 2012"></div> <div class="name4 charity 2012"></div> </div> <div> <div class="name5 home 2010"></div> </div> <div> <div class="name6 work 2007"></div> </div>

i utilize info attributes create filtering easier.

<div class="name1 home" data-year="2013">2013</div> <div class="name2 work" data-year="2012">2012</div> <div class="name3 home" data-year="2012">2012</div> <div class="name4 charity" data-year="2012">2012</div> <div class="name5 home" data-year="2010">2010</div> <div class="name6 work" data-year="2007">2007</div>

the using jquery , array.map (could replaced foreach if want older browser support)

var studies = $('[data-year]') studies.map(function(index, el) { var $el = $(el) year = $el.attr('data-year') if($('#' + year).length == 0){ $(document.body).append( $('<div>').attr('id', year) .css('margin-bottom', '20px') ) } $('#' + year).append(el) })

what take elements data-year attribute, foreach element check see if div id of elements year exists. if doesn't create 1 , append body. appends element year container.

see jsfiddle

javascript filtering

No comments:

Post a Comment