Search code examples
javascriptjqueryonclickimage-size

Javascript - Onclick toggle between image size


I have multiple images, say image A, image B and image C. When I click image A I want it to enlarge. When I then click on image B I want image A to revert back to its original size and B to enlarge.

Here is the codepen im working off: https://codepen.io/anon/pen/BWXrEv

Help would be much appreciated.

Html Code:

<img class="image" src="http://images.e-flux- 
systems.com/646a999d89943180a9b4916b17fd7bac.jpg,2000" alt="" />

<img class="image" src="http://images.e-flux- 
systems.com/2012_09_01the_internet.jpg,1440" alt="" />

Css:

.image {
 width: 150px;
}

.image.enlarge {
 width: 600px;;
}

JS:

 $(document).ready(function() {
   $('.image').click(function() {
    $(this).toggleClass('enlarge');
   });
  });

Solution

  • I think a quick fix is to remove the .enlarge class from all images before adding the class to another image. Try this:

    $(document).ready(function() {
       $('.image').click(function() {
        $('.image').removeClass('enlarge');
        $(this).addClass('enlarge');
       });
      });
    

    Hopefully this works!

    Also, you have an extra semicolon in your CSS, so watch out for that!