svobol13
svobol13

Reputation: 1960

Trigger hover on multiple elements

#red, #blue {
    position: absolute;
    width: 100px;
    height: 100px;        
}
div:hover {
    background-color: yellow !important;
}
#red {
    background-color: red;
}
#blue {
    background-color: blue;
    top: 50px;
    left: 50px;
} 


<div id="red"></div>
<div id="blue"></div>

Is it possible to trigger hover event on multiple elements under cursor without using javascript? How can I make both squares yellow in this simple example?

Upvotes: 1

Views: 1787

Answers (3)

Deryck
Deryck

Reputation: 7668

Pretty little demo

Well all these answers are just SWELL so I'm throwing mine in just for kicks n giggles.

Wrap them into a blanket. Hover the blanket, you change both to yellow.

HTML

<div id="wrap">
    <div id="red"></div>
    <div id="blue"></div>
</div>

CSS

#red, #blue {
    position: absolute;
    width: 100px;
    height: 100px;
}
#red {
    background-color: red;
}
#blue {
    background-color: blue;
    top: 50px;
    left: 50px;
}
#wrap:hover > div {
    background-color: yellow !important;
}

Upvotes: 4

Praveen
Praveen

Reputation: 56509

You can do like

#red:hover {
    background-color: yellow !important;
}

#red:hover + #blue {
    background-color: yellow !important;
}
#blue:hover + #red {
        background-color: yellow !important;
}

JSFiddle

#red:hover + #blue // triggers hover for another element

Upvotes: 1

Ming
Ming

Reputation: 4588

Because you want to be able to select preceding elements, you cannot do this with CSS alone. CSS cascades down the tree, not up the tree. You can do this with JS though.

http://jsfiddle.net/x7cWq/1/

$('div').hover(function() {
    $('div').addClass('yellow');
});

$('div').mouseleave(function() {
    $('div').removeClass('yellow');
});

With CSS:

div:hover, 
.yellow {
    background-color: yellow !important;
}

Upvotes: 1

Related Questions