Changing Opacity with jQuery
Solution 1
The problem is that .gallery-single
is an ancestor of the anchor (i.e. it's outside the anchor). The $(selector, this)
format looks for the selector within this
. Instead, use .closest()
:
$(this).closest('.gallery-single').css(...);
Sidenote: jQuery gives this warning about mouseover
(also applies to mouseout
):
This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.
You should use mouseenter
(and mouseleave
) instead (or the hover()
function which conveniently combines the two).
Solution 2
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 });
});
Ian
Updated on July 09, 2022Comments
-
Ian almost 2 years
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?
-
Ian almost 13 yearsAh yes this works too, and so doesBox9's method, but I only have one choice to tick who's correct lol
-
Michael Robinson almost 13 yearsIf both were helpful, upvote them both, and accept the one that you feel was most helpful.