Search code examples
javascriptjqueryarrayssetintervalfade

How to fade in images using jQuery?


first question.

Basically, I’ve made an array of images and managed to loop it through randomly in order to change the background. It works fine. At set intervals and everything. But the transition is too sudden/jarring.

How can I make it fade in and out slowly please? Thats the whole code relating to that, there is even a button to trigger the change rather than wait. I’d like to make that fade in too! thank you.

var backs= [ "bike-1505039_1280.jpg",

"bananas-698608_1280.jpg",

"camera-813814_1280.jpg",

"chevrons-937583_1280.jpg",

"music-1283877_1280.jpg",

"pattern-26442_1280.png",

"people-2587310_1280.jpg",

"puppy-1903313_1280.jpg",

"road-166543_1280.jpg",

"stone-1664918_1280.jpg",

"street-1209403_1280.jpg",

"technology-2643270_1280.jpg"
];

setInterval(function() {

      $("BODY").css("background-image", "url(" + backs[Math.floor(Math.random() * backs.length)] + ")");
}, 10000);



$("#backChange").on('click', function(event) {
  $("BODY").css("background-image", "url(" + backs[Math.floor(Math.random() * backs.length)] + ")");
});


Solution

  • Since you're using the image as background for the body, I suggest to use CSS3 for the background property:

    Please take a look at this post: CSS3 Fade Effect