DEV Community

artydev
artydev

Posted on • Edited on

Filtering with CSS

Chris Coyer shows a nice tip on filtering with CSS.
In the following example I use his technique and also show how to create a custom element with Swiss

HTML Part

<script src="https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.min.js"></script> <s-users count = 100></s-users> 

JS Part

const element = swiss.element; function view(users) { return ` <input type="text" id="filter" class="input" placeholder="search user..."> <style id="cssFilter"></style> <ul> ${users} </ul> `; } function FakeUsers(el) { const count = parseInt(el.getAttribute("count")) let users = [...Array(count)]; users = users.map(() => faker.name.findName()); listUsers = users.map((u) => `<li data-name="${u}">${u}</li>`).join(""); return view(` <style>li{display: none;}</style> <div>${listUsers}</div>` ); } swiss.element("s-users", FakeUsers); window.filter.addEventListener("input", e => { let filter = e.target.value; let css = filter ? ` li[data-name*="${filter}" i] { display: list-item; } ` : ``; window.cssFilter.innerHTML = css; }); 

You can play with it here : CssFilter

Top comments (0)