Robert
Robert

Reputation: 315

Background image load with animation

I use a little script for showing images as backgrounds inside divs. The problem is that I need some animation for this but nothing I have tried works, my actual script is this:

var valimg="image_1.jpg";
jQuery("#sw_pic").css("background-image",""+valimg);
jQuery("#sw_pic").fadeIn(2000);

The problem, for example, is when I run this, it doesn't generate the fade effect, also I tried jQuery's animate() but with the same result. Only opacity seems to work, but no other.

How I can use this or write code that works finally and get some effect when loading images as background?

Regards and thank´s for the help

Upvotes: 1

Views: 2658

Answers (2)

Sudharsan S
Sudharsan S

Reputation: 15393

Image load slow

The problem is Suppose you set an background image in html the image loads lazy on first time and next time may it works on with browser cache. you try to load the image on dom elements when ready.

Important in html tag load the image like this

<img src="/path/image_1.jpg"  style="display:none"/>

your Jquery inside in dom ready

$(function() {
  var valimg="image_1.jpg";
  jQuery("#sw_pic").css("background-image",""+valimg);
  jQuery("#sw_pic").fadeIn(2000);
});

Upvotes: 0

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

Try to use .hide()

var valimg="image_1.jpg";
jQuery("#sw_pic").css("background-image",'url('+ valimg +')');
jQuery("#sw_pic").hide().fadeIn(2000);

or you can take a look at https://stackoverflow.com/a/4631006/3385827

Upvotes: 3

Related Questions