Show results only on search mode

637 views Asked by At

I'm using a library ListJs to perform fuzzy search and is working perfectly, but there is only one issue, I want the results only show when the user is searching and not showing all results how most of the examples of the documentation is showing.

I can't find any example for what I'm looking, is it possible ListJs have an option that makes results available only one search mode?

HTML:

<div id="sandbox">
    <input class="form-control form-control-lg fuzzy-search" placeholder="Search" />     
    <ul class="list" id="list"></ul>
</div>

JS:

var options = {
    valueNames: [ 
        'productTitle', 
        'productBrand', 
        { name: 'productImage', attr: 'src' }
    ],
    item: '<li>
             <img src="" class="img-fluid productImage" style="height: 100px;" alt="#" />
             <h3 class="productTitle"></h3>
             <p class="productBrand"></p>
           </li>'
};

var userList = new List('sandbox', options);

$.getJSON( "data.json", function( data ) {
    userList.add(data);
});
1

There are 1 answers

0
Elbarto On

Ok so i am not sure i understood what you wanted but i will give it a go since you didn't get a single answer yet.

What i think you want : By default the list is hidden. When the user focus the search field, the list shows up. When focus is lost, the list is hidden again.

You can solve this problem with some js (you could use jquery for selectors and hide() show() methods) :

HTML :

<div id="users">
  <input class="search" placeholder="Search" />
  <button class="sort" data-sort="name">
    Sort by name
  </button>

  <ul class="list">
    <li>
      <h3 class="name">Jonny Stromberg</h3>
      <p class="born">1986</p>
    </li>
    <li>
      <h3 class="name">Jonas Arnklint</h3>
      <p class="born">1985</p>
    </li>
    <li>
      <h3 class="name">Martina Elm</h3>
      <p class="born">1986</p>
    </li>
    <li>
      <h3 class="name">Gustaf Lindqvist</h3>
      <p class="born">1983</p>
    </li>
  </ul>

</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>

JS :

// Listjs
var options = {
  valueNames: [ 'name', 'born' ]
};

var userList = new List('users', options);

// Show/hide on focus
var searchField = document.getElementsByClassName('search')[0];
var listDiv = document.getElementsByClassName('list')[0];

// Hide the list by default 
listDiv.style.visibility = 'hidden';

document.addEventListener('DOMContentLoaded', function() {
    searchField.addEventListener('focus', function() {
        // Search input focused
      listDiv.style.visibility = 'visible';
    });
});

document.addEventListener('DOMContentLoaded', function() {
    searchField.addEventListener('focusout', function() {
        // Search input not focused
      listDiv.style.visibility = 'hidden';
    });
});

Here is a link to a codepen, example based on another example of listjs website.
Hope this helps, Cheers !