Amy Lee
Amy Lee

Reputation: 275

Jquery - Trying to hide and show bunch of images

I'm having slight problem with my jquery code. I'm new to Jquery, so please help me improve my code. Well I'm trying to hide and show this 4 images. Let me elaborate it a bit:

  1. I created this 4 images (put side by side)
  2. When one clicked it should expand and hides the other
  3. When the expanded click it should return to its normal dimension and shows the other
  4. Then it should be repeated

My code seems to work on the first go, but it messes up on the second run (the images doesn't behave like what i envision them to behave)

Here is my code: http://codepen.io/sallyiee/pen/onkKs

Upvotes: 1

Views: 48

Answers (2)

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Try

$(".showcase img" ).click(function(e) {
    if( $(this).hasClass('expand')) {
      $(this).removeClass("expand").addClass("normal").show("fast");
      $(this).siblings().show("fast");
    } else {
      $(this).addClass("expand").removeClass("normal");
      $(this).siblings().hide("fast");
    }
  });

http://codepen.io/tamilcselvan/pen/HpbiK

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You can simplify your code with toggleClass and toggle metods:

$(".showcase" ).on("click", "img", function(e) {
    $(this).toggleClass("expand");
    $(this).siblings().toggle("fast"); 
});

Demo: http://codepen.io/anon/pen/mlBEI

Upvotes: 3

Related Questions