JSFiddle - React, Tailwind, and code Playground
by rami7250
HTML
<h2>My Phonebook</h2>
<input
type="text"
id="myInput"
onkeyup="filterList()"
placeholder="Search for names.."
title="Type in a name"
/>
<ul id="myUL"></ul>
CSS
* {
box-sizing: border-box;
}
#mytopbar {
background-position: 10px 12px;
width: 100%;
font: 18px Arial, sans-serif;
padding: 10px;
border: 1px solid #000;
background:#114559;
margin-bottom: 12px;
color:white;
font-weight:bold;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 12px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myUL {
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block;
}
#myUL li a:hover:not(.header) {
background-color: #eee;
}
JavaScript
const items = [
{ year: 2016, class: 'a', name: 'Adele' },
{ year: 2014, class: 'b', name: 'Agnes' },
{ year: 2015, class: 'a', name: 'Billy' },
{ year: 2016, class: 'a', name: 'Bob' },
{ year: 2016, class: 'c', name: 'Calvin' },
{ year: 2012, class: 'a', name: 'Christina' },
{ year: 2018, class: 'c', name: 'Cindy' },
];
function filterList(list = items) {
const input = document.getElementById('myInput');
const filter = input.value.toUpperCase();
const ul = document.getElementById('myUL');
ul.innerHTML = '';
if (filter) {
ul.innerHTML = `<div id="mytopbar">
<table>
<td class="rt" id="name" >Name</td>
<td class="rt" id="class">Class</td>
<td class="rt" id="year">Year</td>
</table>
</div>`;
document.getElementById('name').addEventListener('click', (event) => {
sortList('name');
});
document.getElementById('class').addEventListener('click', (event) => {
sortList('class');
});
document.getElementById('year').addEventListener('click', (event) => {
sortList('year');
});
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (item.name.toUpperCase().includes(filter.toUpperCase())) {
const keys = Object.keys(item);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const li = document.createElement('li');
const a = document.createElement('a');
li.insertAdjacentElement('beforeend', a);
a.text = item[key];
a.href = '#';
ul.insertAdjacentElement('beforeend', li);
}
...