Boris
Boris

Reputation: 641

JQuery background transition effect

I have a simple jquery code. You click on the icon and it changes the background image with code like this:

$('div').css({'background-image':'url()'});

How can I use animations with it? I searched google but did not really find anything that helps me.

Upvotes: 0

Views: 2677

Answers (2)

Anj D
Anj D

Reputation: 92

    $("div").css({'background-image': 'url(http://lorempixel.com/400/200)'}).animate({height: '300px', opacity: '0.4'}, "slow").animate({width: '300px', opacity: '0.8'}, "slow");

this is some jquery method chaining.

Upvotes: 0

Sajith
Sajith

Reputation: 1269

If you want to fadeIn, it can be done by jquery and CSS. I did it in a way that can be used in dynamic situations, you just have to change background-image in jquery and it will do everything, also you can change the time in CSS.

Html:

<div class="test">

CSS :

.test {
  /* as default, we set a background-image , but it is not nessesary */
  background-image: url(http://lorempixel.com/400/200);
  width: 200px;
  height: 200px;
  /* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
  transition: linear all 1s;
  /* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
  -webkit-transition-delay: 1s;/* Safari */
  transition-delay: 1s;
}

JS:

$('.test').click(function() {
  //you can use all properties : background-color  - background-image ...
  $(this).css({
    'background-image': 'url(http://lorempixel.com/400/200)'
  });
});

I don't think this can be done using jQuery's animate function because the background image does not have the necessary CSS properties to do such fading. jQuery can only utilise what the browser makes possible.

Also, you can try background image positioning as an animation method. https://snook.ca/archives/javascript/jquery-bg-image-animations

Demo: https://snook.ca/technical/jquery-bg/

Upvotes: 1

Related Questions