erezT
erezT

Reputation: 186

JQuery addClass for CSS animation not working

I am trying to animate an img within a div by adding a class, what am I doing wrong?

Thanks.

Please see my JSfiddle.

CODE:

HTML

<div class="loader"></div>
<div class="searchWrapper">
  <div class="row">
    <div class="col-xs-3">
      <img src="http://images.hayneedle.com/mgen/master:AMD010.jpg?is=70,70,0xffffff">
    </div>
  </div>

CSS

    .searchWrapper div > img {
  opacity: 0;
  position: relative;
}

.animate-opacity {
  transition: opacity 8s;
  opacity: 1;
  position: relative;
}

JS

function init() {
  $(".searchWrapper div > img").addClass('animate-opacity', function() {
    console.log('Animation complete.');
  });
}
init();

EDIT:

I jave another script which is the page loader and it's running a set interval function, maybe that's the culprit? since i'm getting in my console starting anim but i'm NOT getting any Animation complete. from the function's callback.

Unfortuneatly on jsfiddle it's working great, but not on my computer. Jsfiddle

Upvotes: 2

Views: 2356

Answers (2)

Alex
Alex

Reputation: 9041

Your CSS for .animate-opacity isn't specific enough, so you have two options:

  1. Give it higher importance:

    .searchWrapper div > img.animate-opacity {

  2. Add the opacity using jQuery:

    jQuery: $(".searchWrapper div > img").css('opacity','1').addClass('animate-opacity', function(){...});

    CSS: .animate-opacity {transition: opacity 8s; position: relative;}

    Example - https://jsfiddle.net/0bv2h7nd/6/

UPDATE

addClass() Doesn't have a callback function, so you'll not be able to use this in you case. You will need to use animate() instead:

$(".searchWrapper div > img").animate({opacity: 1}, 8000, function() {
  console.log('Animation complete.');
});

Example - https://jsfiddle.net/0bv2h7nd/24/

Upvotes: 0

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

Your CSS isn't specific enough (read more about CSS specificity).

Change

.animate-opacity {

To

.searchWrapper div > img.animate-opacity {

Updated Fiddle

Upvotes: 2

Related Questions