Skip to main content

Searching / Filtering Using Javascript And CSS3 Trick

By April 29, 2017Blog, CSS, CSS3, Javascript, Vanilla
Allure Web Solutions Code Snippet

How to implement a simple CSS based search using only JavaScript. There aren’t many use cases for this functionality, but if it matches what you’re trying to accomplish, it’s blazing fast and lean. There are some limitations which include only being able to search for what appears in the data-index attribute.

Demo

See the Pen Search / Filtering Using Javascript And CSS3 Trick by Mike Doubintchik (@allurewebsolutions) on CodePen.

The HTML

 <!-- Search box -->
    <input type="text" placeholder="Search" id="search">

    <!-- Search results displayed inside these style tags !-->
    <style id="search-results"></style>
    
    <!-- Sample data -->
    <table>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
      </tr>
      <tr class="searchable" data-index="jon snow">
        <td>Jon</td>
        <td>Snow</td>
      </tr>
      <tr class="searchable" data-index="james bond">
        <td>James</td>
        <td>Bond</td>
      </tr>
      <tr class="searchable" data-index="shawn the sheep">
        <td>Shawn</td>
        <td>The Sheep</td>
      </tr>
      <tr class="searchable" data-index="yo yo ma">
        <td>Yo Yo</td>
        <td>Ma</td>
      </tr>
    </table>
  </div>

The JavaScript

// define variable
var searchResults = document.getElementById("search-results");
var searchBox = document.getElementById("search");

// add even listener to the search box
searchBox.addEventListener("input", function() {
  // if no results found, search results are empty
  if (!this.value) {
    searchResults.innerHTML = "No results";
    return;
  }

  // if characters typed in search box don't match any data-index, hide with display: none
  searchResults.innerHTML =
    '.searchable:not([data-index*="' +
    this.value.toLowerCase() +
    '"]) { display: none; }';
});

// Credits: http://www.redotheweb.com/2013/05/15/client-side-full-text-search-in-css.html
allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017