I want to add mouse hover effect. Its a product section which has the same div tags, if i hover on the image class, i want to show the title only for the current image but its showing all the title on mouseover.
Below code works onm ouseover but enable all the class name = "highlight". If i hover on the first div =('top-section'), the script should enable only the first class="highlight" name inside it.
Html
<div class ="featured">
<div class="featured-section">
<a href="#" class="featured-link">
<div class="top-section">
<img src="1.jpeg">
<span class="highlight">
<h3 class="title">title 1</h3>
</span>
</div>
</a>
</div>
<div class="featured-section">
<a href="#" class="featured-link">
<div class="top-section">
<img src="2.jpeg">
<span class="highlight">
<h3 class="title">title 2</h3>
</span>
</div>
</a>
</div>
<div class="featured-section">
<a href="#" class="featured-link">
<div class="top-section">
<img src="3.jpeg">
<span class="highlight">
<h3 class="title">title 3</h3>
</span>
</div>
</a>
</div>
</div>
Script
$(".top-section").on({
mouseenter: function () {
$(".highlight").addClass("show").fadeIn();
},
mouseleave: function () {
$('.highlight').removeClass("show").fadeOut();
}
});
CodePudding user response:
The issue is because you select all .highlight
elements in the DOM when the events fire. You need to select only the ones relevant to the .top-section
which fired the event.
To do that use the this
keyword in the event handler to refer to the element which raised the event, then find()
from there:
That being said, it's worth noting that your logic can be created more effectively, and more performantly using CSS alone:
.highlight {
opacity: 0;
height: 0px;
display: block;
transition: opacity 0.3s, height 0.3s;
}
.top-section:hover .highlight {
opacity: 1;
height: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="featured">
<div class="featured-section">
<a href="#" class="featured-link">
<div class="top-section">
<img src="1.jpeg">
<span class="highlight">
<h3 class="title">title 1</h3>
</span>
</div>
</a>
</div>
<div class="featured-section">
<a href="#" class="featured-link">
<div class="top-section">
<img src="2.jpeg">
<span class="highlight">
<h3 class="title">title 2</h3>
</span>
</div>
</a>
</div>
<div class="featured-section">
<a href="#" class="featured-link">
<div class="top-section">
<img src="3.jpeg">
<span class="highlight">
<h3 class="title">title 3</h3>
</span>
</div>
</a>
</div>
</div>
CodePudding user response:
You could do something like this:
$(".top-section").on({
mouseenter: function () {
// .children() creates a jquery object containing all the childrens of the
// current instance of .top-sector, .last() selects the last of them
$(this).children().last().addClass("show").fadeIn();
},
mouseleave: function () {
$(this).children().last().removeClass("show").fadeOut();
}
});