Reputation: 173
When the user clicks on a search box, the user sees a "blinking cursor" inside the search box.
I'd like, when the user presses the Esc key, the "blinking cursor" should leave search box and also focus out from search box.
I need JavaScript code to do it.
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 .ng');
background-position: 10px 10px;
background-repeat: no-repeat;
padding: 12px 20px 12px 40px;
-webkit-transition: width 0 .s ease-in-out;
transition: width 0 .s ease-in-out;
}
input[type=text] :ocus {
width: 100%;
}
<p>Animated search form :/p>
<form>
<input type="text" name="search" placeholder="Search .">
</form>
Upvotes: 1
Views: 11485
Reputation: 5176
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>
Upvotes: 6
Reputation: 4346
Since you mentioned jQuery - here is the solution for that.
$('input[type=text]').keyup(function(e) {
if (e.keyCode === 27) $(this).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%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Animated search form:</p>
<form>
<input type="text" name="search" placeholder="Search..">
</form>
Upvotes: 2