Reputation: 9407
I need to display a div whenever an input box is in focus, and I need this div to be hidden when it is not is focus. I tried the following, but it does not work:
$(document).ready(function() {
if ($("#inputPassword").is(":focus")){
$("#passwordInfo").css("display", "block");
}
else {
$("#passwordInfo").css("display", "none");
}
});
#passwordInfo
is the div I am attempting to alter the display.
Upvotes: 0
Views: 1024
Reputation: 26434
It's better to listen for the focus
and blur
events in your case.
focus
: Fired when an input element gains focus. For example, when a user clicks on an input element
blur
: Fired when an input element loses focus. For example, when a user clicks outside of the input element.
var div = $("#text");
div.hide();
$("#input-field").on("focus", function() {
div.css({ "display": "block" });
}).on("blur", function() {
div.css({ "display": "none" });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input-field" />
<div id="text">This is text</div>
This can actually be simplified using show()
and hide()
$("#input-field").on("focus", function() {
div.show();
}).on("blur", function() {
div.hide();
});
Or combined into one function
var div = $("#text");
div.hide();
$("#input-field").on("focus blur", function(event) {
div.toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input-field" />
<div id="text">This is text</div>
Upvotes: 1
Reputation: 1091
The if ($("#inputPassword").is(":focus"))
code only runs when the document is first ready, so a check is not performed repeatedly.
What you are looking for are the .focus()
and .blur()
functions.
$(document).ready(function() {
$("#inputPassword").focus(function() {
$("#passwordInfo").css("display", "block");
});
$("#inputPassword").blur(function() {
$("#passwordInfo").css("display", "none");
});
});
Upvotes: 1