Flickdraw
Flickdraw

Reputation: 683

Apply the hover state to multiple divs when another div is hovered over

I'm looking for a way to apply the hover state to a selection of divs on my page when another div is hovered over with the mouse.

Hopefully this code will help explain what I need a bit better...

CSS
​#hovered_div {
position:absolute;
width:50px;
height:50px;
margin-top:25px;
margin-left:25px;
background-color:blue;   
}
#hovered_div:hover {
background-color:red;   
}

#div1 {
position:absolute;
width:50px;
height:50px;
margin-top:100px;
margin-left:100px;
background-color:yellow;   
}
#div1:hover {
background-color:green;
width:75px;    
}

#div2 {
position:absolute;
width:50px;
height:50px;
margin-top:100px;
margin-left:25px;
background-color:pink;   
}
#div2:hover {
background-color:black;
height:250px;    
}

#div3 {
position:absolute;
width:50px;
height:50px;
margin-top:25px;
margin-left:100px;
background-color:purple;   
}
#div3:hover {
background-color:grey;
width:150px;    
}

HTML

​<div id="hovered_div"></div>
​<div id="div1"></div>
​<div id="div2"></div>
​<div id="div3"></div>​​​​​​​​​​​​​​​​​​​​​​   

jsFiddle

So, what I'm hoping to achieve is, when the "hovered_div" is hovered over with the mouse, the hovered state for that div, and the other three divs gets applied, and when the mouse moves off, they all go back to normal. ​

Can anyone help me?

Upvotes: 1

Views: 1973

Answers (2)

BlueBird
BlueBird

Reputation: 1466

I would recommend using css class instead of :hover. This will allow you to set the class attribute on mouseover and on mouse out. JS Fiddle Example

$('#hovered_div').mouseover(
  function () {
      $('#div1').attr('class','hover');
      $('#div2').attr('class','hover');
      $('#div3').attr('class','hover');
  });

$('#hovered_div').mouseout(function() {
 $('#div1').attr('class','');
    $('#div2').attr('class','');
      $('#div3').attr('class','');

});

You must change your css to the following (change ':hover' to '.hover')

#div1.hover {
 background-color:green;
width:75px;    
}

Revised way of doing the same

$("#hovered_div").mouseover(function() {
    $('#div1').attr('class', 'hover');
    $('#div2').attr('class', 'hover');
    $('#div3').attr('class', 'hover');
}).mouseout(function() {
    $('#div1').removeClass('hover');
    $('#div2').removeClass('hover');    
    $('#div3').removeClass('hover');

});

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

:hover effects can only be applied to child elements.

Upvotes: 0

Related Questions