BWSnippet

random image using jQuery

random image using jQuery

How to get a random image using jQuery

jquery random image

HTML

<h1>Random Image</h1>
<ul id="imgChangerList">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

jQuery / Javascript

	var backgroundImages = ["honMoon1.jpg","honMoon2.jpg","honMoon3.jpg"];
	var currentNum = 1;

	$(document).ready(function() {

		$('#imgChangerList li').live('click', function() {
	    	$('body').css('backgroundImage' , 'url("resources/images/' + backgroundImages[$(this).index()] + '")' );
		});
	});	
	
	
	function getRandomNum( array  )
	{
		var number =  Math.floor(Math.random() * ( array.length - 1) );

		if(currentNum == number)
		{
			while( currentNum == number )
			{
				number = 1 + Math.floor(Math.random() * ( array.length - 1) );
				console.log( "while currentNum " + currentNum + " number " + number);
			}
		}
		currentNum = number;
		return number;
	}

if you care to see an example,   here is an example project .

Tags

random image using jQuery