Search code examples
javascriptjquerycsstransition

Why does not transition work when removing and adding the class to the same element using removeClass() and addClass()?


There are 2 images that the first one has "opacityOne" class and when a button is clicked , according to a variable called index i want the current image to fade in and the other fade out.

It works fine when "opacityOne" is removed from one and added to another image but when i want to remove and add the "opacityOne" to the same element, i don't see it working and no fading in and out occurs. I was thinking transition would work because i remove and add a class from the element and i don't understand why it doesn't work.

How can i make the same element to fade in and out by removing and adding its class?

HTML:

 <div class="sideImgContainer">
   <div class="imgs clearfix">
     <img src="pics/pcfullimage.png" class="firstImg opacityOne"/>
     <img src="pics/sideimage3.png" class="secondImg"/>
   </div>
 </div>

CSS:

.sideImgContainer img{
   transition: all 1.2s;
   opacity: 0;
 }
 .sideImgContainer .opacityOne{
   opacity:1;
 }

jQuery:

prevBut.click(moveSlide);
nextBut.click(moveSlide);

function moveSlide(){
   secondImg.removeClass("opacityOne");
   firstImg.removeClass("opacityOne");

  if(index === 2 || index === 0){
     firstImg.addClass("opacityOne");
     }
  else{
     secondImg.addClass("opacityOne");
  }
}

Solution

  • Is it not a timing issue? You are removing and adding the class straight away so the transition won’t have even happened. Could you test by wrapping the if statement in a setTimeout() to trigger after 1200ms?