EdwardBlack EdwardBlack - 7 months ago 52
Javascript Question

Change attribute of multiple elements on hover by using CSS

I have two div elements which are placed next to each other, i want to change the attribute

background-color
of both of them if the user hovers over one of them.

So the background-color should be initially set to
#d8d8d8
for both divs and should change to
#cacaca
on both divs if i hover over one of the divs.

I solved it using jquery:



$("#FOO").hover
(
function()
{
$(this).css("background-color","#CACACA");
$("#BAR").css("background-color","#CACACA");
},
function()
{
$(this).css("background-color","#D8D8D8");
$("#BAR").css("background-color","#D8D8D8");
}
)

$("#BAR").hover
(
function()
{
$(this).css("background-color","#CACACA");
$("#FOO").css("background-color","#CACACA");
},
function()
{
$(this).css("background-color","#D8D8D8");
$("#FOO").css("background-color","#D8D8D8");
}
)

.buttons {
border:1px solid black;
background-color: #D8D8D8;

height: 100px;

font-family: play;
font-size: 30px;

text-align:center;
vertical-align: middle;
line-height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="col-xs-10 buttons" id="FOO" style="border-right: 0px">
<span style="padding-left:100px">FOO</span>
</div>
<div class="col-xs-2 buttons" id="BAR" style="border-left: 0px">
<span>BAR</span>
</div>





Is there a better way to achieve this? Maybe only with css?

Answer

You can wrap columns in div and add :hover on it:

.buttons {
  border:1px solid black; 
  background-color: #D8D8D8;

  height: 100px;

  font-family: play;
  font-size: 30px;

  text-align:center;
  vertical-align: middle;
  line-height: 100px; 
}

.row:hover > .buttons {
    background-color: #CACACA;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class='row'>
  <div class="col-xs-10 buttons" id="FOO" style="border-right: 0px">
    <span style="padding-left:100px">FOO</span>
  </div>
  <div class="col-xs-2 buttons" id="BAR" style="border-left: 0px">
    <span>BAR</span>
  </div>
</div>