Home > Software engineering >  How to only show hover on div with same class name, but only on current div
How to only show hover on div with same class name, but only on current div

Time:12-20

So I am trying to display a hidden div onto an existing div, but only have the div that mouse is over be shown. I have a jsfiddle with it showing the error. On hover, it shows all the divs unhidden, but I only want the current div to be visible, and not all of them.

style:

  background-color: blue;
  color: red;
  width: 100px;
  height: 100px;
  position: relative;
}
.productHover{
      position: absolute;
      top: 20px;
      left: 0;
      width: 100%;
      height: 100%;
      display: none;
      color: white;
}

HTML:

Apple
  <div >
    0.1%
  </div>
</div>

<div >
Apple2
  <div >
    0.2%
  </div>
</div>

<div >
Apple3
  <div >
    0.3%
  </div>
</div>

Jquery:

    function() {
        $('.productHover').show();
    }, function() {
        $('.productHover').hide();
    }
 );

jsfiddle: https://jsfiddle.net/spaLo6zf/12/

The divs have the same class name, I am trying to only show one productHover at a time, and now all at same time.

CodePudding user response:

Change your jQuery to:

$('.product').hover(
  function() {
    $(this).find('.productHover').show();
  },
  function() {
    $(this).find('.productHover').hide();
  }
);
.product {
  background-color: blue;
  color: red;
  width: 100px;
  height: 100px;
  position: relative;
}

.productHover {
  position: absolute;
  top: 20px;
  left: 0;
  width: 100%;
  height: 100%;
  display: none;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  Apple
  <div >
    0.1%
  </div>
</div>

<div >
  Apple2
  <div >
    0.2%
  </div>
</div>

<div >
  Apple3
  <div >
    0.3%
  </div>
</div>

  • Related