Reputation: 123
I am making a photo gallery using jQuery and I want to have a button to display a random picture taken from the ones in the album. This picture should change every time the user clicks on the button. I have this code but every time I press the button I have the div#images fulling with the images instead of each one every time.
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
});
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;
});
</script>
As you can see I read the images from a JSON file and randomize from 1 to the length of the file. Any suggestions would be helpful. Thank you in advance.
Upvotes: 0
Views: 251
Reputation: 14363
You need to clear the image div before adding the new image otherwise the images will keep adding.
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
//Also, move the code inside getJson(). getJson is asynchronous.
//Clear the images HTML
$('#images').empty();
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;
});
});
</script>
Just wondering : Why don't you retrieve 1 random image via json call, instead of fetching all the images and then choosing one (Write the randomization code at the server) ?
Upvotes: 3
Reputation: 3951
Does the JSON data change? Otherwise, why do a request everytime? Separating the rand
and image
vars below isn't necessary, but might be easy to read for others later.
$('button').on('click', function() {
if ( typeof imageList == 'undefined' || !imageList.length )
{
$.getJSON('images.json', function(data) {
imageList = data;
var rand = Math.floor(Math.random() * imageList.length) + 1;
var image = $('<img />').attr('src', imageList[ rand ].img_src );
$('#images').html( image );
});
}
else
{
var rand = Math.floor(Math.random() * imageList.length) + 1;
var image = $('<img />').attr('src', imageList[ rand ].img_src );
$('#images').html( image );
}
});
Upvotes: 2
Reputation: 3650
Make sure you close the image tag as well as clear the existing image
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
});
$('#images').html("");
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '/>');
});
</script>
Upvotes: 0