0

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.

http://jsfiddle.net/xXqhH/

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Working Demo

2 Comments

Thanks. Yes, I had been using .click(). I take it this method is possibly preferable to James's method due to the CSS being visible independent of the script?
I generally prefer to use classes, but it depends. For a single CSS property, it doesn't make much difference; if you're changing multiple then a class is just that much easier. It does also separate things out that bit more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.