Reputation: 55
I am new to javascript. I made a simple code that in javascript will randomly change my background every 5 seconds, however, it looks horrid.
Both of loading the picture and the transition is jumpy and doesn't look nice at all. When I google this problem all the code looks super complicated, I am not allowed to use external links for help either(it's a school project).
What I want is to implement crossfading transitions into my code, and I have seen people do it using CSS but for that, you have to add every single picture and blah blah blah, I want it to be reusable, for me to write it once and then if I add more pictures I won't have to change anything, hope you guys understand and hope you can help!!! :)
Code:
function random_pic() {
// image array
var images = ["url(1.jpg)", "url(2.jpg)", "url(3.jpg)", "url(4.jpg)"];
// execute code every 5 seconds
window.setInterval(function() {
// create a random number between 0 and 4
var num = Math.floor(Math.random() * 4);
// set the background to one of the images in the array
document.body.style.backgroundImage = images[num];
},
5000);
}
random_pic();
Upvotes: 1
Views: 814
Reputation: 343
I'm reading that you have two different issues that you are trying to solve. The biggest issue is the crossfading issue. The other issue is the performance and loading of the images.
As this is a school assignment I think it's not a good idea to share the exact code that will make this work, but I'll give you some pointers that you can use to get to the desired result.
Hope this helps. Good luck.
Upvotes: 3