Change Images Randomly with Pure-JavaScript and jQuery
There are two methods to change image: 1- Change your image randomly with pure javascript. 2- Change your images randomly with jquery.
by Aqeel Malik
HTML
<p>Random Image with JavaScript</p>
<img id="img" src=""/>
<br><br>
<br><br>
<p>Random Images with jQuery</p>
<img class="changeMe" src="" />
<img class="changeMe" src="" />
<img class="changeMe" src="" />
<img class="changeMe" src="" />
<img class="changeMe" src="" />
<br><br>
<img src="http://images.clipartpanda.com/dog-clipart-puppy_dog_with_bone.png" />
<img src="http://sweetclipart.com/multisite/sweetclipart/files/imagecache/middle/baby_chick_yellow.png" />
<img src="http://images.clipartpanda.com/cute-cat-clipart-cat_kitten_cute_orange.png" />
CSS
/*
Company : Webicosoft.com
Name : Aqeel Malik (Web Developer)
Email : [email protected]
Mobile : +92 302 6262164
Skills : xHTML | HTML5 | CSS3 | Bootstrap | Wordpress | Javascript | jQuery | Ajax | AngularJS | Jekyll | PHP+MySQL | Photoshop | Firework | Dreamweaver
*/
img {max-width:100px}
img.changeMe {max-height:50px}
JavaScript
/* RONDOM IMAGE with JAVASCRIPT */
function WT_RANDOM_IMAGE() {
var imgArray = [
"http://www.gravatar.com/avatar/",
"https://jsfiddle.net/favicon.png",
"https://jsfiddle.net/img/logo.png"
];
return imgArray[Math.floor(Math.random() * imgArray.length)];
}
setInterval(function() {
document.getElementById("img").src = WT_RANDOM_IMAGE();
}, 1000);
/* RONDOM IMAGES with JQUERY */
$.fn.WT_RANDOM_IMAGE = function (n) {
var images = [
"http://images.clipartpanda.com/dog-clipart-puppy_dog_with_bone.png",
"http://sweetclipart.com/multisite/sweetclipart/files/imagecache/middle/baby_chick_yellow.png",
"http://images.clipartpanda.com/cute-cat-clipart-cat_kitten_cute_orange.png"
];
return images[Math.floor(Math.random() * (n + 1))];
}
setInterval(function() {
$(".changeMe").each(function() {
$(this).attr('src', $.fn.WT_RANDOM_IMAGE($(".changeMe").length));
});
}, 1000);