1

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

An0nC0d3r
  • 1,275
  • 13
  • 33
Robert
  • 315
  • 2
  • 5
  • 9

2 Answers2

3

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

Community
  • 1
  • 1
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

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);
});
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49