How can I alert a message once the input is focused, of the following HTML code:
<div class="ss_datesel_inp_cont">
<div class="ss_datesel_inp_right_corner"> </div>
<input autocomplete="off">
</div>
This is what I tried but none works:
$(".ss_datesel_inp_cont:input").click(function() {
alert("focused");
});
// or
$(".ss_datesel_inp_cont:input").focus(function() {
alert("focused");
});
//or
$(".ss_datesel_inp_cont").find("input").focus(function() {
alert("focused");
});
The
:inputselector will only work if the the given element is an input (also textarea, select, and others). The.ss_dateseletc. class is not on the input, it’s on the div. You can simply use a descendant selector instead:However, this will only work if click the input. If you focus it by tabbing or automatically, the alert won’t occur. Problem is, if you use
.focus,alert()steals the focus and then reapplies it in some browsers and you will be stuck in a focus loop. Here’s a simple solution:Note that not all browsers will restore focus after an alert, even if you try to force them to. You may want to use some alternative to
alert, especially because that would be really annoying to users.You can also update
.data('focused')tofalseon blur so this happens over again.