开发者

Change CSS for parent div when child element (input field) is selected

I'm looking to change the class of a parent div when a child input text field is selected or the mouse moves over any of the other elements in the container. I've tried using both jQuery and some of the pseudo classes in CSS to no avail.

开发者_如何学编程

Javascript:

$("input").focus(function () {
     $(this).parent().parent("div").css('background-color','#666');  
});

HTML:

    <div class="container_to_change">
            <div class="box1">
                &nbsp;
            </div>
            <div class="box2">
                <input type="text" class="data-entry">
            </div>
            <div class="box3">
                &nbsp;
            </div>
    </div>


As @Ibu suggests, in his comment to the question, you could simply use the :hover pseudo-class to effect a change in the container_to_change element (depending on what change you wish to apply):

.container_to_change:hover {
    background-color: #ffa;
}

JS Fiddle demo

If, however, you really want to use jQuery for this:

$('.container_to_change').hover(
    function(){
        $(this).addClass('newClassName');
    },
    function(){
        $(this).removeClass('newClassName');
    });

JS Fiddle demo.


Edited in response to question, in comments, from wishIdidntsquishthatfish:

How do you keep the different state though when the user is interacting with the input element inside?

$('.container_to_change').hover(
    function(){
        $(this).addClass('newClassName');
    },
    function(){
        if ($(this).find('input').is(':focus')){
            return false; // if the input has focus, prevent the removal of the class-name.
        }
        $(this).removeClass('newClassName');
    }).find('input').focus(
    function(){
        // ensures that the class-name is added in response to keyboard-navigation focus
        $(this).closest('.container_to_change').addClass('newClassName');
    }).blur(
    function(){
        // ensures that the class-name is removed in response to keyboard-navigation focus
        $(this).closest('.container_to_change').removeClass('newClassName');
    });

JS Fiddle demo.

References:

  • :hover pseudo-class.
  • hover().
  • addClass().
  • removeClass().
  • :focus.
  • focus().
  • blur().


I don't think you need to specify "div" when trying to get the parent of a parent.

$('input').focus(function(){
    $(this).parent().parent().css('background-color', '#666');
});

But why do you care about parents? You can easily just say:

$('input').focus(function(){
    $('.container_to_change').css('background-color','#666');
});

And if you're worried about specific input classes, just use:

$('.data-entry').focus(function(){
    $('.container_to_change').css('background-color','#666');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜