Archi Patel Archi Patel - 1 month ago 8
CSS Question

fixing focus out on pressing a "esc" key

when user click on search box. user see a "blinking cursor" inside search box.

need like, when user press "esc" key "blinking cursor" should leave search box and also focus out from search box.

plz need javascript code to do it. tx



input[type=text] {
width: 130px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 16px;
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
padding: 12px 20px 12px 40px;
-webkit-transition: width 0.4s ease-in-out;
transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
width: 100%;
}

<p>Animated search form:</p>

<form>
<input type="text" name="search" placeholder="Search..">
</form>




Answer

Using document.getElementById("search").blur() when "esc" is pressed works just fine, where "search" is an id given to the search box.

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {//27 is the code for escape
        document.getElementById("search").blur(); 
    }
};
input[type=text] {
    width: 130px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url('searchicon.png');
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
    width: 100%;
}
<p>Animated search form:</p>

<form>
  <input id="search" type="text" name="search" placeholder="Search..">
</form>