Reputation: 1029
I have a 'gallery' of images with a selection button below each. When I click on the button related to each image, I want the image opacity to change to 0.5. I'd rather do this without each image having an individual id. Warning: my jQuery knowledge is pretty average, I cant quite get my head around some of it!
<div>
Group 1<br>
<img src="http://www.example.com/myimage1.png" class="my-img" /><br>
<button class="mybutton">Click</button>
</div>
<br>
<div>
Group 2<br>
<img src="http://www.example.com/myimage2.png" class="my-img" /><br>
<button class="mybutton">Click</button>
</div>
So, with code like this, clicking any button will fade ALL images with that class, not just the related image
$('.mybutton').click(function(){
$('.my-img').css("opacity","0.5");
});
I thought about using something like .prev() but I don't think I have my head wrapped around it properly and am implementing wrong.
$('.mybutton').click(function(){
$(this).prev('.my-img').css("opacity","0.5");
});
Any thoughts on how to approach this?
https://jsfiddle.net/sanfly/gbkz566b/3/
Upvotes: 2
Views: 3430
Reputation: 5967
prev()
only gets the immediately preceding sibling, and that is the <br>
tag. Your selector is looking for an element with the class my-img
. As the <br>
tag does not have this class the query wouldn't return anything.
Since there's only one button and image per parent you could use siblings()
instead.
$('.mybutton').click(function() {
$(this).siblings('.my-img').css("opacity", "0.5");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Group 1<br>
<img src="https://i.sstatic.net/Hl3Y0.png" class="my-img" /><br>
<button class="mybutton">
Click
</button>
</div>
<br>
<div>
Group 2<br>
<img src="https://i.sstatic.net/Hl3Y0.png" class="my-img" /><br>
<button class="mybutton">
Click
</button>
</div>
Upvotes: 0
Reputation: 50316
The previous element to the button is a br
. So in this case you have to go to the root that is the parent and find the child that is img and change it's opacity
$('.mybutton').click(function() {
$(this).parent().find('img.my-img').css("opacity", "0.5");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Group 1
<br>
<img src="https://i.sstatic.net/Hl3Y0.png" class="my-img" />
<br>
<button class="mybutton">
Click
</button>
</div>
<br>
<div>
Group 2
<br>
<img src="https://i.sstatic.net/Hl3Y0.png" class="my-img" />
<br>
<button class="mybutton">
Click
</button>
</div>
Upvotes: 1