From 0dcace1bab7527cc2e745d22bd834803cf7c8d5c Mon Sep 17 00:00:00 2001 From: Shy Date: Mon, 6 May 2024 14:29:30 +0200 Subject: [PATCH] Outsource counting to other functions --- static/index.js | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/static/index.js b/static/index.js index dfcb014..a79b6dd 100644 --- a/static/index.js +++ b/static/index.js @@ -17,6 +17,7 @@ function renderItems() { const container = document.getElementById('results'); const template = document.getElementById('item'); const loading = document.getElementById('loading'); + let count = 0; for (const [id, item] of Object.entries(items)) { const clone = template.content.cloneNode(true); @@ -32,11 +33,13 @@ function renderItems() { clone.querySelector("a").href = `form.html?id=${encodeURIComponent(id)}`; if (item.hidden) { clone.querySelector(".result").classList.add('hidden') - }; + } else { + count++; + } container.appendChild(clone); }; loading.remove(); - updateCounter(); + updateCounter(count); } function getLocString(items, item) { @@ -68,6 +71,7 @@ function search(e) { const searchAttrs = ['id', 'name', 'type', 'note', 'content']; const query = e.target.value; const regex = new RegExp(query, 'i') + let count = 0; for (const elem of document.getElementsByClassName('result')) { const item = items[elem.id.slice(5)]; @@ -86,31 +90,26 @@ function search(e) { if (found) { elem.classList.remove('filtered'); + count++; } else { elem.classList.add('filtered'); } } - updateCounter(); + updateCounter(count); } -function updateCounter(){ - let count = 0; - - for (const elem of document.getElementsByClassName('result')) { - if (!elem.matches('.filtered')) { - count++; - } - } +function updateCounter(count){ + const itemcount = document.getElementById('itemcount'); switch(count) { case 0: - document.getElementById('itemcount').textContent = 'No items found.'; + itemcount.textContent = 'No items found.'; break; case 1: - document.getElementById('itemcount').textContent = '1 item found.'; + itemcount.textContent = '1 item found.'; break; default: - document.getElementById('itemcount').textContent = `${count} items found.`; + itemcount.textContent = `${count} items found.`; break; } }