How To Randomly Change Inline Images On Page Load And Each Refresh, Using Jquery?
Solution 1:
I found solution here
http://www.robwalshonline.com/posts/jquery-plugin-random-image-on-page-load/
Solution 2:
jQuery by itself can not read a folder's contents. Unless you do some magic like name the files for example 1.jpg, 2.jpg and include an upperbound in the script.
You should probably use a server side language to read the folder and pass some JSON to your JavaScript. Then just loop the JSON and display.
$.getJSON('get/files', function(data) {
$.each(data, function(image) {
$('#my-div ul').append('<li><img src="' + image + '" alt="" />');
});
});
Solution 3:
I guess it would depend on how many pics you are talking about and if they will change frequently. Let's say there aren't many and the list will stay pretty much the same. You could through their file names into an array and then randomly generate a number based on the length of the array's index.
$(document).ready(function() {
var rndNumber;
var displayPictures = newArray();
displayPictures[0...n] = 'filename.jpg';
rndNumber = (Math.floor(Math.random()*displayPictures.length));
$('#picture_tag_id_name').attr('src', 'images/'+displayPictures[rndNumber]);
});
When I tried this on a site, I used inline PHP to loop through the contents of the image folder and 'echo' out the lines that populate the array with the strings of all the image paths.
May not be the best way but it is a way.
Post a Comment for "How To Randomly Change Inline Images On Page Load And Each Refresh, Using Jquery?"