0

I'm trying to make an instant search box. When user start typing in the search box, it triggers a javascript event to hide the blog posts (#home) and search results will be shown instead (this part of the script is not included below). However, after user cleared the search box, they see just a blank page as the display of #home is still set to be none.

How can I make JavaScript detect the user cleared the input filed at #search-input and make #home display true again?

document.getElementById('search-input').oninput = function() {
    document.getElementById('home').style.display = 'none';
};

enter image description here enter image description here enter image description here

2 Answers 2

3

You can do this through the input event listener. To hide the #home element, add a conditional to check if the input has a value. If it doesn't then you hide it. To bring it back you do the opposite but only if #home is hidden:

const searchInput = document.getElementById('search-input');
const home = document.getElementById('home');

searchInput.addEventListener('input', function() {
    if (!this.value) {
        home.style.display = 'none';
    } else if (this.value && home.style.display === 'none') {
      home.style.display = 'block';
    }
});
<input id="search-input" type="text"/>

<div id="home">
  Sample Content
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Glad I was able to help out. Good luck!
0

Thanks for the help of Carl Edwards!

Here is the final code that works perfectly:

const searchInput = document.getElementById('search-input');
const home = document.getElementById('home');
const results = document.getElementById('results');

searchInput.addEventListener('input', function() {
    if (this.value) {
        home.style.display = 'none';
        results.style.display = 'inline';
    } else if (!this.value && home.style.display === 'none') {
      home.style.display = 'block';
      results.style.display = 'none';
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.