Show and hide input for javascript search field

1

Hi, I'm doing the site search bar and the bar template and so: it has an image of a magnifying glass and when you click on the image, under it appears the input to type the search. I'm doing this in JavaScript but I'm having problems. It happens so when I click the input appears more when I click outside it is still there, how can I make it disappear I tried to use if and else, for loops more I did not get anything. Can anybody help me? Thanks!

<script>
function mostrarPesquisa(){
  document.getElementById('pesquisa').style.display="inline-block";
 }
</scripit>

  <div id="menu">
    <div id="dentromenu">
        <ul class="menu">
            <li class="activeItem"><a><img class="lupa" src="imagens/lupa.png" alt="Lupa" onClick="mostrarPesquisa()"></a>
                <div id="caixapesquisa">
                    <form id="formpesquisa" action="" method="get">
                        <input id="pesquisa" class="pesquisa" type="text" value="" maxlength="" placeholder="Pesquisar..."><input id="btnpesquisa" type="hidden" src="imagens/lupa.png" value=""> 
                    </form>
                </div>
            </li>
    
asked by anonymous 21.10.2015 / 21:03

2 answers

3

You will need 2 events:

1) onclick in the magnifying glass image. When clicking, change the display property of the input so that it appears on the page (apparently, your code already does this)

2) onblur in the search input. The onblur event is executed when the element loses focus. This way, when the input loses focus, change the property display to none

Change in your HTML:

<input id="pesquisa" class="pesquisa" type="text" value="" maxlength="" placeholder="Pesquisar..." onblur="esconderCampoPesquisa()">

and add this function:

function esconderCampoPesquisa() {
   this.style.display = 'none';
}

Obs: Your input element should be hidden initially. Add a CSS class to it by setting display to none

    
21.10.2015 / 21:16
2

You can use an EventListener:

document.getElementById("pesquisa").addEventListener("blur", myFunction);

function myFunction() {
    document.getElementById("pesquisa").style.display = "none";
}
    
21.10.2015 / 21:19