Reputation: 153
I have multiple divs with different id names, like this:
<div id="person1">
<img class="imgPerson" src="../images/person1.jpg">
<div class="personBubble" style="display: none;">
<div class="extraInfo">
Sells carrots
</div>
</div>
</div>
<div id="person2">
<img class="imgPerson" src="../images/person2.jpg">
<div class="personBubble" style="display: none;">
<div class="extraInfo">
Sells onions
</div>
</div>
</div>
<div id="person3">
<img class="imgPerson" src="../images/person3.jpg">
<div class="personBubble" style="display: none;">
<div class="extraInfo">
Sells lettuce
</div>
</div>
</div>
As you can see, I have person1, person2, person3
.
I also have this jQuery function that sets display:block
for the personBubble
class when imgPerson
is on hover.
$(".imgPerson").hover(
function () {
$(".personBubble").fadeIn(150);
},
function () {
$(".personBubble").fadeOut(150);
});
However, obviously every personBubble
class is set to display:block
when the event is activated, since they all have the same name. I only want this to happen to the corresponding personBubble
, i.e. if the imgPerson
of person1 is on hover, only the personBubble
of person1 should be set to display: block
.
What is the best way to achieve this without having to use unique IDs for every person and having to write the same jQuery function for each one of those IDs?
Upvotes: 1
Views: 965
Reputation: 21
since imgPerson
and personBubble
are siblings, all you have to do is use siblings()
and I suggest you use fadeToggle() it makes your code shorter, shorter is better.
$(".imgPerson").hover(function(){
$(this).siblings().fadeToggle(150);
});
Upvotes: 0
Reputation: 6002
You can refer to the this
object which points to the current context and call siblings()
method to search for a sibling with respective class name .personBubble
inside current context.
$(".imgPerson").hover(
function () {
$(this).siblings(".personBubble").fadeIn(150);
},
function () {
$(this).siblings(".personBubble").fadeOut(150);
}
);
Upvotes: 3
Reputation: 148110
You can use event source object using $(this)
to get next personBubble
$(".imgPerson").hover(
function () {
$(this).next(".personBubble").fadeIn(150);
},
function () {
$(this).next(".personBubble").fadeOut(150);
});
Upvotes: 2