SearchForKnowledge
SearchForKnowledge

Reputation: 3751

How to set opacity of an image respective to the DIV it is in

I have the following HTML:

<div class="mmItemStyleChild">
    <img src="theImages/home.png" class="mIcon vertAlign mmm1" id="mH1" /> <img src="theImages/emptyImg.png" class="mSpacerStyle" /><span id="mH" class="vertAlign mmm">Home</span>
</div>
<div class="mmItemStyleChild">
    <img src="theImages/MakeAnAppt_icon.png" class="mIcon vertAlign mmm1" id="mMW1" /> <img src="theImages/emptyImg.png" class="mSpacerStyle" /><span id="mMW" class="vertAlign mmm">My WESTMED</span>
</div>
<div class="mmItemStyleChild">
    <img src="theImages/FindaProvider_icon.png" class="mIcon vertAlign mmm1" id="mFP1" /> <img src="theImages/emptyImg.png" class="mSpacerStyle" /><span id="mFP" class="vertAlign mmm">Find a Provider</span>
</div>

I would like the image on the left to be animated opacity by 35% when the text on the right is hovered, and then back to normal when the mouse leaves.

So for example, if I hover over Home, the home image should be animated.

I have the following JQuery which does something similar:

$(".mmm {home}").hover(function(){
    $("{.mmm1 [HOME]}").stop().animate({"opacity": .35}); //on text hover set it at 35% opacity
},function(){
    $("{.mmm1 [HOME]}").stop().animate({"opacity": 1}); //on text hover leave set it to default opacity
});

How do I make it so that each text will only work on the image on the same DIV

Upvotes: 3

Views: 93

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50797

$('.mmm').hover(function(){
    $(this).closest('div').find('.mIcon').stop().animate({'opacity': .35});
}, function(){
    $(this).closest('div').find('.mIcon').stop().animate({'opacity': 1});
});

.closest() will traverse the dom for the closest element, which in this case will be the parent (you could also use .parent() here). Then .find() will traverse it's children to find the element. The rest is the same as your code. This will make sure that the animations only affect the image associated with the text you hover.

Upvotes: 4

Try this

$('.mmItemStyleChild span').hover(function() {
    var $img = $(this).siblings('.mm1'); // define image object;

    $($img).stop().animate({
        opacity: .35
    });
}, function() {
    var $img = $(this).siblings('.mm1'); // define image object;
    $($img).stop().animate({
        opacity: 1
    });
}); 

Upvotes: 1

Related Questions