I have a UI that needs a class added to input containers if they are focused or have any text inside. I use jQuery to add/remove the class depending on focus state but the script also needs to run once on load in case the value is already filled in.
jQuery(document).ready(function($){
var $jsInputs = $('.js-input');
// Listeners
$jsInputs.on('focusin', function(e) {
var $input = $(this),
$parent = $input.parent();
$parent.addClass('is-active');
});
$jsInputs.on('focusout', function(e) {
var $input = $(this),
$parent = $input.parent();
if (!$input.val()) {
$parent.removeClass('is-active');
}
});
// Run once to check for input already present
$jsInputs.each(function(i,e) {
if ($(e).val()) {
$(e).parent().addClass('is-active');
}
})
})
This works fine for values added by the application itself but struggles with values autofilled by the browser. So far I've tried waiting until window.onload
and triggering a focusin
and focusout
event programatically on the inputs, but none of those methods detect the autofilled text.
Is there a way to reliably read autofilled values in JS (vanilla or jQuery)? Disabling autofill could be a last resort but I really don't want to go there from a UX perspective...