简体   繁体   中英

jQuery change css of an element when another element becomes active

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/

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM