0

I want my images to double in size when clicked, and return to normal size when clicked again. What's working: I successfully add the "unzoomed" class to the correct images. When the images are clicked, they have the "unzoomed" class removed and the "zoomed" class added to them, and they double in size. When I click them again, nothing happens.

You can view the problem here. Just click on any of the images.

Here is my HTML:

<figure>
        <img src="./images/certcentral/certcentral01.png" class="image-outline">
        <figcaption>Fig. 1: The certification experience.</figcaption>
</figure>

Here is my CSS:

figure img {
margin-left: 0px;
max-width: 400px;
transition: transform .4s;
}

.unzoomed:hover {
cursor: zoom-in;
}


.zoomed {
transform: scale(2);

}


.zoomed:hover {
cursor: zoom-out;
}

Here is my jQuery:

<script>
$(document).ready(function(){

    $("figure img").addClass("unzoomed");

    $("figure img.unzoomed").click(function(){
        $(this).addClass("zoomed").removeClass("unzoomed");
    });

    $("figure img.zoomed").click(function(){
        $(this).addClass("unzoomed").removeClass("zoomed");
    });

});
</script>
devigner
  • 142
  • 10
  • 3
    Because there are no elements with class zoomed at the time you're attaching the event listeners. Use event delegation instead of attaching events directly to the elements. – Teemu Aug 13 '18 at 05:02
  • 1
    Possible duplicate of [jQuery on click event not working on toggled class](https://stackoverflow.com/questions/18973524/jquery-on-click-event-not-working-on-toggled-class) – Sebastian Simon Aug 13 '18 at 05:03
  • Oh, weird, that makes sense! Well, the part about why it doesn't work. I don't know what event delegation is. I got it to work using toggleClass. Thanks for the help! – devigner Aug 13 '18 at 05:18
  • 1
    Event delegation is a technique, where you attach an event listener to an ancestor element of the element(s) of which events you want to listen to. – Teemu Aug 13 '18 at 05:25
  • Okay, that's a little over my head still, I'm VERY new to this. Is this technique advantageous to the toggleClass option? I now start with the element having class unzoomed, and on click I toggleClass unzoomed and toggleClass zoomed. I have noticed the animation to zoomed in is a bit choppy, not as smooth as I'd hoped. – devigner Aug 13 '18 at 06:43
  • 1
    `toggleClass` goes well in your case. Using event delegation would have caused a minimal change only to your code, but you've already made the changes, it's not worth to change it again. For the further information of event delegation, see https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation – Teemu Aug 13 '18 at 07:20

0 Answers0