Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

49
Views
How to have input/search bar eventlisteners not fire off so much

I have a search bar at the top of my page where I want to have the user look for a specific query and then the page will hide all blog posts that do not contain that query. However, I have an issue where I have an eventListener listening for input within my search bar but when I console.log out a value in one of my callback functions in the eventListener, it fires off a LOT. I believe this is an issue that is affecting a crucial part of my website so I hope to fix it soon.

Here is my initialization code for the client-side javascript:

function init() {
    makeCardRequest();
    let input = qs('#search-term');
    input.addEventListener('input', updateSearchButton);
    let home = qs('#home-btn');
    home.addEventListener('click', goHome);
  }

Here is the chain of callback functions for the input:

  function updateSearchButton() {
    let button = qs('#search-btn');
    if (this.value.trim() !== '') {
      button.disabled = false;
      button.addEventListener('click', () => {
        search(this.value);
      });
    } else {
      button.disabled = true;
    }
  }

  async function search(query) {
    qs('#search-btn').disabled = true;
    let cards = qsa('article');
    for (let i = 0; i < cards.length; i++) {
      cards[i].classList.add('hidden');
    }
    console.log(cards);
    let home = qs('#home');
    home.classList.remove('hidden');
    fetch('yipper/yips?search=' + query)
      .then(statusCheck)
      .then(res => res.json())
      .then(processData)
      .catch(console.error);
  }

Where I notice the issue is that when I log out cards in my search function, it logs it out into the console for each character I put in the search bar. For example, if I search 'Hello', it will log the cards out 5 times.

7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs