I'm trying to affect only one class by hovering another element withing the same parent. There are many parents/elements with the same class name and I only need to target one inside of each to implement a hover effect. I'm trying to use .find(), but it doesn't work for some reason. And if I don't use .find(), it starts targeting all ".team-title" class elements on a page.
<div class="team-parent">
<div class="team-memeber"></div>
<div class="team-title"></div>
</div>
<div class="team-parent">
<div class="team-member"></div>
<div class="team-title"></div>
</div>
<div class="team-parent">
<!-- ... -->
</div>
$(".team-member").hover(function() {
$("this").find(".team-title").animate({"marginLeft": "15px"}, 400);
}, function() {
$("this").find(".team-title").animate({"marginLeft": "0px"}, 400);
});
Firstly you need to use this
as a keyword, not a string. Secondly find()
is used to locate child elements, whereas the element you're trying to target is a sibling, as such you can use next()
, like this:
$(".team-member").hover(function() {
$(this).next(".team-title").animate({
"marginLeft": "15px"
}, 400);
}, function() {
$(this).next(".team-title").animate({
"marginLeft": "0px"
}, 400);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="team-parent">
<div class="team-member">Member 1</div>
<div class="team-title">Team 1</div>
</div>
<div class="team-parent">
<div class="team-member">Member 2</div>
<div class="team-title">Team 2</div>
</div>
That being said, there is no need for JS here, as what you're trying to achieve can be done more effectively in CSS:
.team-title {
margin-left: 0;
transition: margin 0.4s;
}
.team-member:hover + .team-title {
margin-left: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="team-parent">
<div class="team-member">Member 1</div>
<div class="team-title">Team 1</div>
</div>
<div class="team-parent">
<div class="team-member">Member 2</div>
<div class="team-title">Team 2</div>
</div>