chris a
chris a

Reputation: 31

hover element if another element is hovered

I've looked around but can't find the right answer for this... How do I set an element to hover, assuming another is hovered?

Where Assuming "selector" is hovered, it will hover, box 1+2 etc...

http://jsfiddle.net/wgJRQ/

<div id="table">
<div id="row">
    <div id="selector">selector 1</div>
    <div id="selector2">selector 2</div>
</div>
<br />
<div id="row">
    <div id="box1">box 1</div>
    <div id="box2">box 2</div>
</div>
<div id="row">
    <div id="box3">box 3</div>
    <div id="box4">box 4</div>
</div>

Upvotes: 3

Views: 95

Answers (3)

Tobia
Tobia

Reputation: 18831

With CSS you can only do it if the "target" element is inside the one being hovered.

In your case, you should change your layout to be arranged in columns instead of rows, so that you have box 1 and box 2 inside selector 1. That way you can change the look of box1 when you hover on its selector: .selector:hover .box1 {...}

If you cannot do this, then you will have to use Javascript.

Keep in mind that you cannot trigger :hover with Javascript, you will have to add a class to the boxes when the mouse enters the selectors, and remove the class when it exits them.

Upvotes: 0

Samuel Liew
Samuel Liew

Reputation: 79113

jQuery:

$('#table > div:first > div')
    .hover(function() {
        $('#table').children('div')
            .eq($(this).index() + 1)
            .children('div')
            .toggleClass('active');
        return false;
    });

http://jsfiddle.net/samliew/pyY5u/

You might want to optimize your hover states and reduce it to a single declaration, something like this:

#table > div:nth-child(n+1) > div {
    border:2px solid #FFFFFF;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: 100px;
}
#table > div:nth-child(n+1) > div:hover,
#table > div:nth-child(n+1) > div.active {
    background-color:#FFFFFF;
    border:2px solid #666666;
}
#box1, #box2 {
    background-color:#E07586;
}
#box3, #box4 {
    background-color:#837C71;
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

Try something like

#box1:hover, #box1:hover~#box2 {
    display: table-cell;
    background-color:#FFFFFF;
    border:2px solid #666666;
    text-align: center;
    vertical-align: middle;
}

Demo: Fiddle

Upvotes: 1

Related Questions