Jeorge Philip Jeorge Philip - 7 months ago 12
HTML Question

How to apply a CSS class to another element when an object is hovered?

I have a project where in a user needs to hover on a product, then the other products will have a class that will filter them black and white. I do know how to put the filter but what I need is that when I hover on a product, it won't go black and white, but the other products will become filtered. What should I do?

Here's my html code:

<div id="wrapper">
<ul>
<li>
<div><a href="#"><img class="grayscale" src="images/product1.png"/></a></div>
<div><span class="product_text">sample product 1</span></div>
</li>

<li>
<div><a href="#"><img class="grayscale" src="images/product2.png"/></a></div>
<div><span class="product_text">sample product 2</span></div>
</li>

<li>
<div><a href="#"><img class="grayscale" src="images/product3.png"/></a></div>
<div><span class="product_text">sample product 3</span></div>
</li>
<ul>
</div>


Here's my CSS code for the class grayscale and the no filter:

img.grayscale:hover {
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
filter: #666666;
-webkit-filter: grayscale(100%);
}

img.grayscale {
filter: none;
-webkit-filter: grayscale(0%);
}


Hope someone can help me. Thanks! :)

Answer

You can't do that with a hover on the image.

What you can do is make all images grayscale when you hover the menu and remove the grayscale from the hovered image.

#wrapper ul:hover img {
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
}
#wrapper ul img:hover {
  -webkit-filter: none;
  filter: none;
  -webkit-filter: grayscale(0%);
  filter: grayscale(0%);
}
#wrapper ul {
  list-style: none;
}
#wrapper ul li {
  display: inline-block;
}
<div id="wrapper">
  <ul>
    <li>
      <div>
        <a href="#">
          <img class="grayscale" src="http://www.fillmurray.com/140/100" />
        </a>
      </div>
      <div><span class="product_text">sample product 1</span>
      </div>
    </li>

    <li>
      <div>
        <a href="#">
          <img class="grayscale" src="http://www.fillmurray.com/140/100" />
        </a>
      </div>
      <div><span class="product_text">sample product 2</span>
      </div>
    </li>

    <li>
      <div>
        <a href="#">
          <img class="grayscale" src="http://www.fillmurray.com/140/100" />
        </a>
      </div>
      <div><span class="product_text">sample product 3</span>
      </div>
    </li>
    <ul>
</div>

Comments