3
votes

I have a bootstrap 4.0 carousel and I want zooming effect when each slides active. I have used transform: scale property for achieving it. I have applied transform: scale to .carousel-item.active img element. And I have added active class for first element using jquery. The animation is not working for my first slide. When it loops it works. I have tried to add the class in setTimeOut function, but it didn't help. Can any one please help me?

These are my codes

html

    <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item">
      <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="https://placeimg.com/640/480/nature" alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="https://placeimg.com/640/480/animals" alt="Third slide">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

css

.carousel-item img{
  transition: all 1s;
  transform:scale(1);
}

.carousel-item.active img{
  transform:scale(1.2);
}

jquery

window.setTimeout(function(){
                $('#carouselExampleControls .carousel-item:first-child').addClass('active');
            },2000);

Here is the fiddle for the same

1

1 Answers

1
votes

I think first you shouldn't change the "active" class by JavaScript, always try and find first a CSS solution only, and put the active class already in the HTML as so:

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="First slide">
    </div>

Also I read somewhere that using animation instead of transform takes much less CPU processing, so go for the keyframes, like this:

@-webkit-keyframes zoom {
    from {
        -webkit-transform: scale(1, 1);
    }
    to {
       -webkit-transform: scale(1.2, 1.2);
    }
}

@keyframes zoom {
    from {
        transform: scale(1, 1);
    }
    to {
        transform: scale(1.2, 1.2);
    }
}

And then the css:

.carousel-inner .carousel-item.active > img {
    -webkit-animation: zoom 1s forwards;
    animation: zoom 1s forwards;
}

Working fiddle: http://jsfiddle.net/v2nc9hx3/