Show and hide input for javascript search field

Asked

Viewed 10,368 times

1

Hi I’m doing the search bar of the site and the model of the bar and like this: has an image of a magnifying glass and when you click on the image, below it appears the input to type the search. I’m doing it in Javascript but I’m having problems. It happens like this when I click appears the most input when I click out it remains there, as I can make it disappear I tried to use if and Else, for loops but I got nothing. Can someone help me? Thank you!

<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>
  • 1

    Would not be display = "none"?

  • 1

    Put more information about your code, the ideal would be to put also html.

  • Yes more when I put the None display, and click off the input continues there, which is quite strange.

2 answers

3


You will need 2 events:

1) onclick image of the magnifying glass. By clicking, change the property display input for it to appear on the page (apparently, your code already does this)

2) onblur in the search input. The event onblur is executed when the element loses focus. That way, when the input loses focus, change the property display for 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 the display for none

  • Thank you very much guy worked!

2

You can use an Eventlistener:

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

function myFunction() {
    document.getElementById("pesquisa").style.display = "none";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.