jQuery randomize picture - javascript

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.

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) ?

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 );
}
});

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>

Related

pre load images using jquery from flickr api

I'm calling a random image from flickr api.
now it's working but user need to wait for image to download,
how can I do a preload of next image so user will see the image right away.
I need to preload just the next image each time,this is my code:
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
//tags: keyword,
tagmode: "any",
format: "json"
});
var loadNewImage = function() {
var rnd = Math.floor(Math.random() * data.items.length);
var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
$('.main').css('background-image', "url('" + image_src + "')");
}
var imageInterval = 10000;
setInterval(loadNewImage(), imageInterval);
});
One way would be to insert a hidden img into the document and handle its onload event.

Pulling a random image from imgur with Javascript

I created a function with the help of some other StackOverflow answers - when the button is clicked, it generates a random image from imgur by using a 5-letter string and adding it to a url. Here's my code: http://codepen.io/kaisle/pen/ojbwQm
function randomString() {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
var stringlength = 5;
var text = '';
for (var i = 0; i < stringlength; i++) {
var rnum = Math.floor(Math.random() * chars.length);
text += chars.substring(rnum,rnum+1);
}
document.getElementById('output').innerHTML = text;
var source = 'http://i.imgur.com/' + text + '.jpg';
$('.stuff img').attr('src', source);
var newimagewidth = $('.stuff img').width;
avoidBrokenImages();
}
This is successful besides the fact that I get the "removed" image a lot, because it's pulling deleted pictures from imgur, or images that never contained the random 5-letter string. To avoid this, I'm trying to create a way to detect this image (http://i.imgur.com/removed.png), which is 161px wide, and then re-run the function until it gets an image that is not 161px wide. I have attempted this in the Codepen above by running the following function at the end of my image generator function:
function avoidBrokenImages(){
var newimagewidth = $('.stuff img').width;
if ($('.stuff img').width() == 161) {
randomString();
} else {
return false;
}
}
This "avoidBrokenImages" function doesn't seem to work because I'm still getting the "removed" image a lot.
Any suggestions? I feel like this is something easy I'm missing.
You're trying to read the image width before it's loaded. You should change
$('.stuff img').attr('src', source);
var newimagewidth = $('.stuff img').width;
avoidBrokenImages();
to
$('.stuff img').attr('src', source).on('load', avoidBrokenImages);
Modified original: http://codepen.io/anon/pen/qObPrq
Slightly cleaned up code: http://codepen.io/anon/pen/KdVXWY

How to reload tile which is not loaded in leaflet.js

I am searching for solution, how to reload tile in leaflet.js which is not loaded due error 503.
Thank you
Looking at the API I put this code together which should help you solve the problem:
function reloadImg() { // reload image by changing its src
var src = $(this).attr("src");
var i = src.lastIndexOf('?');
if(i > 0) { // remove previous cache string
src = src.substring(0, i);
}
$(this).attr("src", src + "?nocache=" + (Math.random() * 1000));
}
map.on('layeradd', function(ILayer) { // on adding a new tile
if($.isFunction(ILayer.layer.getContainer)) { // get the container holding the images
$("img", ILayer.layer.getContainer()).error(reloadImg); // apply error handling event
}
});

Loading A text along with a picture using AJAX

I have made a photo gallery in my website using the following:
/*Begin Photo Gallery Code*/
var images = ['g1.jpg', 'g2.jpg', 'g3.jpg', 'g4.jpg'];
function loadImage(src) {
$('#pic').fadeOut('slow', function() {
$(this).html('<img src="' + src + '" />').fadeIn('slow');
});
}
function goNext() {
var next = $('#gallery>img.current').next();
if(next.length == 0)
next = $('#gallery>img:first');
$('#gallery>img').removeClass('current');
next.addClass('current');
loadImage(next.attr('src'));
}
$(function() {
for(var i = 0; i < images.length; i++) {
$('#gallery').append('<img src="images/gallery/' + images[i] + '" />');
}
$('#gallery>img').click(function() {
$('#gallery>img').removeClass('current');
loadImage($(this).attr('src'));
$(this).addClass('current');
});
loadImage('images/gallery/' + images[0]);
$('#gallery>img:first').addClass('current');
setInterval(goNext, 4000);
});
It loads one picture at a time from a set of four pictures. Also I have four html files, each of them being relevant to one of the pictures. I want to use JavaScript/JQuery/AJAX to load the relevant html file's content along with the shown picture. Does anyone have an idea how I can do this?
Should I put the ajax files (4 html files) into a JavaScript array or something?
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];
Thanks in advance.
Unless the HTML files supposed to change somehow during their displaying, should either output them via your server-side code in hidden divs with the request (would be the correct way of doing it) or use AJAX to save them in a variable or create hidden divs.
First you need two arrays like this:
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];//File Names
var divPages=['div1','div2','div3','div4'];//Div ids in order
For the AJAX part you should use something like:
var getHtml = function(filename,divid){
$.post('html/'+filename, function(data) {
//The first argument is your file location
//Second one is the callback, data is the string retrieved
$('#'+divid).html(data);
});
}
$.each(ajaxPages,function(index,value){
getHtml(value,divPages[index]);
});
That should do it... Do tell me if you require further explanation.
EDIT:
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];
var divId="yourdivid";
var textArray=new Array();
var currentImg=0;
var getHtml = function(filename){
$.post('html/'+filename, function(data) {
textArray.push(data);//Save data inside the array textArray
});
}
$.each(ajaxPages,function(index,value){
getHtml(value,divPages[index]);
});
Then your goNext() method:
function goNext() {
var next = $('#gallery>img.current').next();
if(next.length == 0){
next = $('#gallery>img:first');
currentImg=0;
}else{
currentImg++;
}
$('#gallery>img').removeClass('current');
next.addClass('current');
loadImage(next.attr('src'));
$('#'+divId).html(textArray[currentImg]);//Adds text to div based on current picture
}
That should be working fine!

Fading background images from an array

$('.pictures a').click(function () {
var path = "place/of/images";
var pics = ['pic1.JPG',
'pic2.JPG',
'pic3.JPG',
'pic4.JPG'];
var i = 0;
var numberOfPics = pics.length - 1;
var vaheta = setInterval(function () {
$('body').css({ backgroundImage: 'url(' + path + pics[i] + ')' });
if (i == numberOfPics) {
i = 0;
} else {
i++;
}
}, 3000);
return false;
});
This is the code that is currently just changing background images for me. Now I found a topic here where it says you have to load the pictures as etc and there was this fiddle, http://jsfiddle.net/RnqQL/1/, this one, that is exactly what I want to do, but I don't quite know how to combine these two (my code and the fiddle).
The images will actually later be loaded with JSON from the server depending on the id of the link the person clicked to get this slideshow, this is too overwhelming for me...
I created fiddle at http://jsfiddle.net/xMrp3/1/
You can modify and use. I try to explain what i did with comments.
$('.pictures a').click(function () {
var path = "http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/";
$("#wrap").empty(); // clear wrap div content
$.getJSON('/echo/json/', function (pics) { // get json data
var pics = ['s-1.jpg', 's-5.jpg', 's-3.jpg']; // i override json response for demo
$.each(pics, function(i, pic) { // loop through pics array
$('<img/>').attr('src', path + pic).appendTo($("#wrap")); // append all images to #wrap div
});
if (animTimeout == null) // if we didnt started anim yet
anim(); // start animation
});
return false;
});
var animTimeout = null;
function anim() {
$("#wrap img").first().appendTo('#wrap').fadeOut(500);
$("#wrap img").first().fadeIn(500);
animTimeout = setTimeout(anim, 700);
}
​

Categories