jQuery to change image opacity onclick

Sanfly

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/

H77

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="http://i.stack.imgur.com/Hl3Y0.png" class="my-img" /><br>
  <button class="mybutton">
Click
</button>
</div>
<br>
<div>
  Group 2<br>
  <img src="http://i.stack.imgur.com/Hl3Y0.png" class="my-img" /><br>
  <button class="mybutton">
Click
</button>
</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related