What is the best way to make this simple filter using jQuery

I am learning jQuery. I made a simple selection filter with basic knowledge in order to learn new methods. My question is, what could be a more complicated way to do this: https://codepen.io/frivolta/pen/LLwjjy

$(".elementFilter li").on("click",eventTrigger);

function eventTrigger(){
  var getFilterName = $(this).attr("class");
  if(getFilterName!="all"){
  $(".elementList li:not([data-category='"+getFilterName+"'])").hide(); 
  $(".elementList [data-category='"+getFilterName+"']").show();
  }else{
     $(".elementList li").show();
  }
}


<div class="elements">
  <ul class="elementFilter">
    <li class="all">Show all</li>
    <li class="filterOne">Filter One</li>
    <li class="filterTwo">Filter Two</li>
    <li class="filterThree">Filter Three</li>
    <li class="filterFour">Filter Four</li>
  </ul>
  <ul class="elementList">

    <li data-category="filterOne">Filter One</li>
    <li data-category="filterTwo">Filter Two</li>
    <li data-category="filterThree">Filter Three</li>
    <li data-category="filterFour">Filter Four</li>
  </ul>
</div>

      

I would like to split functions and pass parameters between them, if you have any advice I would love to hear that. Thanks, F.

+3


source to share


1 answer


Your code is almost perfect, but it won't work if you change adding some other class to li elements. See my code below. I showed the problem with the solution.



$(".elementFilter li").on("click",eventTrigger);

function eventTrigger(){
  var isClasssAll = $(this).hasClass("all");
  var getFilterName = $(this).attr("data-category");

  if(!isClasssAll){
  $(".elementList li:not([data-category='"+getFilterName+"'])").hide(); 
  $(".elementList [data-category='"+getFilterName+"']").show();
  }else{
     $(".elementList li").show();
  }
}



<div class="elements">
  <ul class="elementFilter">
    <li class="all asdasd">Show all</li>
    <li data-category="filterOne" class="filterOne 1">Filter One</li>
    <li data-category="filterTwo" class="filterTwo 2">Filter Two</li>
    <li data-category="filterThree" class="filterThree 3">Filter Three</li>
    <li data-category="filterFour" class="filterFour 4">Filter Four</li>
  </ul>
  <ul class="elementList">

    <li data-category="filterOne">Filter One</li>
    <li data-category="filterTwo">Filter Two</li>
    <li data-category="filterThree">Filter Three</li>
    <li data-category="filterFour">Filter Four</li>
  </ul>
</div>

      

+2


source







All Articles