Black
Black

Reputation: 20212

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?

Upvotes: 3

Views: 2348

Answers (2)

Upperface
Upperface

Reputation: 121

I would give both divs the same css-class like so:

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

Then in jquery you can make the following rule:

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

You are more flexible this way.

Upvotes: 3

t1m0n
t1m0n

Reputation: 3431

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>

Upvotes: 5

Related Questions