Nrc
Nrc

Reputation: 9787

Fade and later, change background with jQuery

I have been searching and it seems that it is not possible to animate background with jQuery.

Then I tried to fade out, change with css and then fade in. I do not understand why it does not follow that order and the css changes first. How can I do that in the order that I mentioned?

(I have a similar effect by putting one div on top of the other and fade the entire div. But for different reasons in the real context, that options have some drawbacks)

$("#boto").click(function() {
		$('#boto').fadeOut(1000)
				  .css('background-image', 'url(https://www.w3.org/html/logo/downloads/HTML5_Logo_256.png)')
				  .fadeIn(1000);
    });
#boto {
	position:absolute;
	top:10px; left:10px;
	width:300px; height:300px;
	
	background-image: url('https://www.w3.org/html/logo/downloads/HTML5_Badge_256.png');
	background-repeat: no-repeat;
	background-position: center;

	background-color:whiteSmoke;
	cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="boto"></div>

Upvotes: 0

Views: 31

Answers (2)

life quality
life quality

Reputation: 65

You can try this:

$('#boto').fadeOut(1000).animate({
    backgroundImage: 'url(https://www.w3.org/html/logo/downloads/HTML5_Logo_256.png),
    display: 'block'
}, 1000);

Upvotes: 0

Phiter
Phiter

Reputation: 14992

You have to wait for the fadeOut to finish, and this should be done by passing a second parameter to the function call, like this:

$("#boto").click(function() {
  $(this).fadeOut(1000, function(){
    $(this).css('background-image', 'url(https://www.w3.org/html/logo/downloads/HTML5_Logo_256.png)')
    .fadeIn(1000);
  });
});
#boto {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 300px;
  height: 300px;
  background-image: url('https://www.w3.org/html/logo/downloads/HTML5_Badge_256.png');
  background-repeat: no-repeat;
  background-position: center;
  background-color: whiteSmoke;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="boto"></div>

Upvotes: 1

Related Questions