Changing Opacity with jQuery

Ian picture Ian · Jun 8, 2011 · Viewed 31.2k times · Source

I have 9 items on a grid, I want all items to have 0.5 opacity on every item and only when hovered over should the div/item and everything inside have 1.0 opacicty.

Here is the JS

$('.gallery-single').css({ opacity: 0.5 });

$('.gallery-single a').mouseover(function(){
    $('.gallery-single-title', this).css('display', 'block');
        $('.gallery-single', this).css({ opacity: 1 });
});
$('.gallery-single a').mouseout(function(){
    $('.gallery-single-title', this).css('display', 'none');
        $('.gallery-single', this).css({ opacity: 0.5 });
}); 

HTML

<div class="gallery-single">
<a href="#" title="">
<div class="gallery-single-title hide">Some text goes here</div>
<div class="gallery-single-img"><img src="http://img.youtube.com/vi/code/0.jpg" width="300" height="200" /></div>
</a>
</div>

All items are at opacity 0.5 when loaded but opacities are not changed when focused. What am I doing wrong here?

Answer

Michael Robinson picture Michael Robinson · Jun 8, 2011

Try this:

$('.gallery-single a').hover(function(){
    $(this).closest('.gallery-single-title').css('display', 'block');
        $(this).closest('.gallery-single').css({ opacity: 1 });
},
function(){
    $(this).closest('.gallery-single-title').css('display', 'none');
        $(this).closest('.gallery-single').css({ opacity: 0.5 });
}); 

Working example.