Home > OS >  Enlarge images by clicking (JQuery)
Enlarge images by clicking (JQuery)

Time:01-25

I want a second class to be added to each image by clicking on it and the image will be the size defined in the second class:

$(document).ready(function() {
  $('.photo_main>img').click(function() {
    $(this).toggleClass('size_img');

  }, function() {
    $(this).toggleClass('.photo_main > img');
  });
});
.photo_main {
  text-align: center;
  margin: 5rem auto 2rem;
  cursor: pointer;
}

.photo_main>img {
  width: 350px;
  height: 250px;
}

.size_img {
  width: 850px !important;
  height: 550px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >

  <img src="http://placekitten.com/350/200" alt="">

</div>

CodePudding user response:

You should use toggleClass instead of addClass or removeClass to add/remove a class based on the fact if the element already has it or not.

https://api.jquery.com/toggleclass/

Then you should fine tune the selector from .photo_main to .photo_main img because you want the click event handler to be on the picture itself so that inside the handler, $(this) will be the img element you want to address to toggle its class.

In the end you should use one function only to attach to the event.

One minor adjustment was removing !important using a selector that wins the specificity over the default size.

Here's your code with the expected behaviour working, where if you click on the picture it will enlarge its size and if you click again it will revert back to its initial size:

$(document).ready(function() {
  $('.photo_main img').click(function() {   
    $(this).toggleClass('size_img');
  });
});
.photo_main {
  text-align: center;
  margin: 5rem auto 2rem;
  cursor: pointer;
}

.photo_main > img {
  width: 350px;
  height: 250px;
}

.photo_main > .size_img {
  width: 850px;
  height: 550px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div >
  <img src="https://pixabay.com/get/gcff1c3f39b9717427535f7ba5991535b7e545da97477390c0135ea11e9cf49ad0ec4887befe05915ec29f9e91bb9022c6780f91059ecfcba12094d3d47df934917143a73a8faeeec06fcdad681bcc960_640.jpg" alt="">
</div>

  • Related