user2963379
user2963379

Reputation: 165

CSS on hover change image from another div

HTML part

   <div class="test">
      <ul>
         <li class="yeah"><a href="#">Link 1</a></li> 
    </div>

    <div class="subject">
      <p>hello</p>
    </div>

CSS

.test:hover + .subject{
  background-color:green;
}

So if I do this, it works. But what I really want to do is using the item inside the list to target the div "subject" and make changes that way. The reason why I'm doing it like this is because I'll have more than one item inside that list and I want each of them to do a certain thing.

My failed attempt:

.test li.yeah:hover + .image{
  background-color:green;
}

Is this even possible? Thanks.

Upvotes: 0

Views: 779

Answers (1)

sandrina-p
sandrina-p

Reputation: 4170

Right now it's only possible to target directly related elements on CSS, so what you want is not possible yet.

With javascript that can be easily done with jQuery:

$sub = $('.subject');
$('.yeah').on({
    mouseenter: function() {
        var i = $(this).index();
        $sub.addClass('li-'+i);
    }, mouseleave: function() {
        $sub.removeClass().addClass('subject');

    }
})
.li-0{
  background-color:green;
}

.li-1{
  background-color:red;
}

.li-2{
  background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
      <ul>
         <li class="yeah"><a href="#">Link 1</a></li> 
        <li class="yeah"><a href="#">Link 1</a></li> 
        <li class="yeah"><a href="#">Link 1</a></li> 
      </ul>
    </div>

    <div class="subject">
      <p>hello</p>
    </div>

Upvotes: 1

Related Questions