Search code examples
htmlcssbootstrap-4jekyll

How to hide an element and only show it when a user starts typing?


I am trying to incorporate a search function into my Jekyll site. I therefor decided to go with with Simple-Jekyll-Search which can be found here: Link.

This is what my search.html looks like:

<input type="text" id="my-search-input" placeholder="Search">

<div class="card">  
  <ul id="my-results-container"></ul>
</div>

<script src="/assets/javascript/simple-jekyll-search.min.js" type="text/javascript"></script>

<script>
SimpleJekyllSearch({
  searchInput: document.getElementById('my-search-input'),
  resultsContainer: document.getElementById('my-results-container'),
  searchResultTemplate: '[...]',
  json: '/search.json',
  noResultsText: '<li><p>No results found!</p></li>'
})
</script>

The search function works great so far. However the borderd card is getting shown even if nothing is getting entered. So the question is:

How can I hide the card and only show it after the user has entered some key strokes?

enter image description here


Solution

  • Hide card class in your stylesheet first.

    .card{
    
    display:none;
    }
    

    and then Add following code in the script tag -

    $(function() {
         $('#my-search-input').keyup(function() {
     if ($(this).val().length == 0) {
    
        $('.card').hide();
      } else {
        $('.card').show();
      }
    }).keyup();
    });
    

    I am assuming you have added jquery in your code - If not please add following code in the head tag

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>