I'm new to JS and trying to make an input field that that only appears when the user types anywhere on the page. Currently, the appearing of the input field works but once it's visible, the user still has to click into the field to type in it.
I would like it to work like:
- User presses "S"
- Field appears with "S" typed in it.
Any help would be much appreciated!
var searchArea = $(".search");
searchArea.hide();
$(document).ready(function() {
$( "body" ).keydown(function() {
searchArea.show();
searchArea.elements['input'].focus();
console.log("worked!");
});
});
I'm new to JS and trying to make an input field that that only appears when the user types anywhere on the page. Currently, the appearing of the input field works but once it's visible, the user still has to click into the field to type in it.
I would like it to work like:
- User presses "S"
- Field appears with "S" typed in it.
Any help would be much appreciated!
http://codepen.io/jeremypbeasley/pen/RNrore
var searchArea = $(".search");
searchArea.hide();
$(document).ready(function() {
$( "body" ).keydown(function() {
searchArea.show();
searchArea.elements['input'].focus();
console.log("worked!");
});
});
Share
Improve this question
asked Dec 6, 2014 at 14:13
Jeremy P. BeasleyJeremy P. Beasley
7091 gold badge7 silver badges22 bronze badges
3 Answers
Reset to default 4What is searchArea.elements['input']
supposed to do ?
Try it like this instead, using jQuery's find
method
$( "body" ).on('keydown', function() {
searchArea.show().find('input').focus();
});
PEN
You need to find
the input
element within the seach area, then call focus()
on it:
$(document).ready(function() {
var $searchArea = $(".search").hide();
$("body").keydown(function() {
$searchArea.show();
$searchArea.find('input').focus();
});
});
Updated CodePen
Or just set id to input field (<input autofocus="autofocus" id="hid_inp"
>)
and use $("#hid_inp").focus();
instead of searchArea.elements['input'].focus();"