Swap background-image with delay via jQuery

Asked

Viewed 267 times

3

I’m trying to make a transition from background images via jQuery, with fade-in and fade-out effect and swapping this image, below follows my code.

$(document).ready(function() {
   $("#player").delay(500).animate({"opacity": "0"}, 1000);
   $("#player").delay(1500).animate({"opacity": "1"}, 1000);
   $("#player").delay(1500).css({'background-image': 'url("PLAYERS/ouro1.png")'}); //linha com problema
} );
.image .player {
   height: 600px;
   width: 380px;
   background-image: url("PACKS/P4.jpg");
   display: flex;
   justify-content: center;
   align-items: center;
   opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="image">
      <div class="player" id="player">
      </div>
</div>

The way the background image looks just doesn’t change, but the fade-in and fade-out effect works.

If I replace ". css(" with ". qcss(" as I found in another problem, the image changes at the moment and does not delay.

1 answer

4


Use animate jQuery has to be careful because starting one on the same element before the other ends results in unexpected behavior.

In this case, it would be better to use the callback in the first animate (start the other animation only when one is finished), and change the image before the second animation:

$(document).ready(function() {
   $("#player")
   .delay(500)
   .animate({"opacity": "0"}, 1000, function(){
      $(this)
      .css('background-image', 'url(https://tinyjpg.com/images/social/website.jpg)')
      .delay(1000)
      .animate({"opacity": "1"}, 1000);
      
   });
} );
.image .player {
   height: 600px;
   width: 380px;
   background-image: url("https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg");
   display: flex;
   justify-content: center;
   align-items: center;
   opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image">
      <div class="player" id="player">
      </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.