Reputation: 750
I am trying to change the background colour of a label adjacent to an input element when the input becomes 'active'.
This will need to work for both clicking to the input and tabbing between input elements.
I was able to get this to work if the user clicked the input, but my solution didn't work if the user tabbed into an input element. I was also having to repeat the code for each input element. Considering I am likely to have quite a few input elements, I figured there must be a more graceful way?
Here is a link with the basic HTML + CSS.
Upvotes: 0
Views: 1672
Reputation: 38345
I lied in my comment - I am going to write this from scratch. I assume the problem you had where it was working with clicking, but not with tabbing, was due to using the .click()
jQuery function. Using .focus()
instead, along with a CSS class, should provide the desired result:
jQuery code:
$('input:text').focus(function(e) {
$('label').removeClass('active');
$(this).prev('label').addClass('active');
});
Extra CSS:
label.active {
background: red !important;
}
Upvotes: 1
Reputation: 165971
Assuming I've understood what you're trying to do correctly, just bind event handlers to the focusin
and focusout
events. You can use prev
to find the immediately preceding sibling, and css
to set a CSS property:
$("input").focusin(function() {
$(this).prev("label").css("background-color", "red");
}).focusout(function() {
$(this).prev("label").css("background-color", "gray");
});
Here's an updated fiddle.
Upvotes: 3