ā–¼
Streaming live at 10am (PST)

Javascript / jQuery: Type anything to show a hidden DIV

Hi, I am working on an input field that has a kind of auto-suggestion function.

This is how I make the .suggestions div appears when the user hits any key. It works, but the function also triggers when the input field is not focused.

$(document).keypress(function(){
$('.suggestions').show();
});

This is what I would like to achieve:
Only when the input field is focused, by entering any character (keypress) and the .suggestions div will show.

I tried using $("#input-id").is(":focus") but not success. I guess I was not doing it correctly.

Any idea? Thanks a lot.

@anthonychan2509 correct me if iā€™m wrong, but this code will trigger on the whole page because its listening to the whole $(document). You might want to change it to the code below and depending on your design, set the input field to Autofocus.

$("#input-id").keypress(function(){
$('.suggestions').show();
});

1 Like

Thanks a lot.

With your inspiration, it works:

$("#input-id").is(":focus").keypress(function(){
$('.suggestions').show();
});