user1665232
user1665232

Reputation: 231

CSS event on one element, changing an other

How can i change an element with CSS with an event on another element?

E.g. <div id="one"> ....., <div id="two">....

<style>
#one:hover
{
changing the visibility of #two...
}
</style>

Upvotes: 3

Views: 9000

Answers (2)

Ana
Ana

Reputation: 37179

In your case, with the element you wish to change being after the element you hover, meaning that you have a structure like:

<div id="one"></div>
<!--you could have some elements between them-->
<div id="two"></div>

or like:

<div id="one">
    <!--maybe some elements-->
        <div id="two"></div>
    <!---->
</div>

In the first case (#one and #two are siblings, that is they are on the same level = have the same parent), you use the general sibling combinator (~), like this:

#one:hover ~ #two { /* style changes */ }

DEMO for the case when #one and #two are siblings and #one is before #two in the HTML.

In the second case (#two is a descendant of #one), you use:

#one:hover #two { /* style changes */ }

DEMO for the case when #two is a descendant of #one.

However, if you wish to change an element that is before #one in the HTML, then that is currently (meaning that this could change in the future) impossible with CSS alone (if you would like to know why, then this article offers an explanation).


But in this case, when #two is before #one in the HTML, you can do it with JavaScript. For instance, if the opacity of #two is initially 0, then you could change it to 1 when hovering #one using:

var one = document.getElementById('one'),
    two = document.getElementById('two');
one.addEventListener('mouseover', function(){
    two.style.opacity = 1;
}, true);
one.addEventListener('mouseout', function(){
    two.style.opacity = 0;
}, true);

DEMO

And if you're using a library like jQuery, then it gets even easier:

$('#one').hover(function(){
    $('#two').css({'opacity': 1})},
function(){
    $('#two').css({'opacity': 0})
});​​

DEMO

Upvotes: 5

Kyle
Kyle

Reputation: 67194

Use a combination of the :hover selector and the ~ General Sibling selector:

div.margin:hover ~.margin2
{
    background: #00f;
}

Hover over div 2 and you'll see the other div change.

For this to work, the divs must be siblings (have the same parent element).

http://jsfiddle.net/Kyle_Sevenoaks/mmcRp/

Upvotes: 3

Related Questions