Skip to content Skip to sidebar Skip to footer

Random Animation Changing Gifs

This post concerns with my previous post: GIFs changing randomly I have 3 different animations next to each other. Each one consist of different gifs which are shown randomly after

Solution 1:

Your problem is that the window.onload is being assigned a new function everytime.

This means that only the last function will 'survive', and will be executed.

You have 2 options:

  • Use window.addEventListener('load',function(){ [code] }), with repeated code
  • Rewrite it to handle an array of elements, with individual intervals

The best option is the 2nd one.

And I've rewritten it here:

window.onload = function () {

	var colors = [
			{name:'red',delay:3000},
			{name:'yellow',delay:1000},
			{name:'green',delay:2300},
			{name:'blue',delay:2600},
			{name:'pink',delay:1300},
			{name:'purple',delay:500},
		],
		elements = document.getElementsByTagName('span'), //the array is here
		change_color = function ( element ) {
			var color = colors[ ( Math.random() * colors.length )>>0 ];

			element.style.color = color.name;

			setTimeout(function(){
				change_color(element);
			}, color.delay);
		};

	for(var i=0, l=elements.length; i<l; i++)
	{
		change_color(elements[i]);
	}

};
<spanstyle="background:black;font-family:sans-serif;font-size:20px;font-weight:bold;padding:10px;">I change color!</span><br><br><br><!-- bad html! --><spanstyle="background:black;font-family:sans-serif;font-size:20px;font-weight:bold;padding:10px;">I change too!</span><br><br><br><spanstyle="background:black;font-family:sans-serif;font-size:20px;font-weight:bold;padding:10px;">Look at me!</span>

This, again, using the same example to change the color of multiple elements.

This can be very easily changed to change the images.

Post a Comment for "Random Animation Changing Gifs"