Change color CSS

Asked

Viewed 4,318 times

1

Good afternoon, I’m with a doubt as I can do to change the color of a div by passing the mouse on another for example:

I have two div with the name of the first div of 1 and the second div with the name of 2 both are give color black, when I pass the mouse in div 2 it changes the color to red in div 2 and in div 1 automatically, would have as someone to help me ?

  • Want to hover over the first and change the color of the second and vice versa ?

2 answers

3


With CSS, provided the element to be changed is child of the element to be made:

div:hover h2 {
  color: red;
}
<div>
  <h1>Olá</h1>
  <h2>Adeus</h2>
</div>

With more freedom, any element activates any other element of the DOM:

$('h1').hover(
    function () {
        $('h2').css({'color': 'red'});          
     },
     function () {
        $('h2').css({'color': 'black'});   
     }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>Olá</h1>
<h2>Adeus</h2>

  • Thank you very much!

  • You’re welcome @Nathan

2

If only to change in div 2 you could use the event :hover of the CSS.

$("#dois").on("mouseover", function() {
  $("#um").css("background-color", "red");
  $("#dois").css("background-color", "red");
});

$("#dois").on("mouseout", function() {
  $("#um").css("background-color", "black");
  $("#dois").css("background-color", "black");
});
.box {
  background: black;
  width: 100px;
  height: 100px;
  color: white;
  font-size: 100px;
  border-radius: 3px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="um" class="box">1</div>
<div id="dois" class="box">2</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.