Skip to content

Instantly share code, notes, and snippets.

@porfidev
Created January 2, 2018 01:47
Show Gist options
  • Save porfidev/94574b4e91e4885e32d9ea83756097bd to your computer and use it in GitHub Desktop.
Save porfidev/94574b4e91e4885e32d9ea83756097bd to your computer and use it in GitHub Desktop.
Cambiar imagen de fondo con las obtenidas de un folder cada determinado tiempo
var folder = "images/";
var availableImages = [];
var time = 4000;
// Ejecutar un AJAX a un folder con las imágenes
// Importante que sea de acceso publico y sin un index.
$(document).ready(function () {
$.ajax({
url: folder,
success: function (data) {
availableImages = findImages(data);
addImageInterval(availableImages, time);
}
});
});
/**
* Busca las imágenes de un folder público
* @param domData
* @returns {Array}
*/
function findImages(domData) {
var imagesFound = [];
$(domData).find('a').attr('href', function () {
if (this.href.match(/\.(jpg|png|gif)$/)) {
imagesFound.push(this.href);
}
});
return imagesFound;
}
/**
* Crea un intervalo de tiempo para cambiar las imágenes obtenidas
* @param images
* @param time
*/
function addImageInterval(images, time) {
var last = 0;
var random;
var total = images.length;
setInterval(function () {
do {
random = Math.floor(Math.random() * total);
} while (last === random);
var safeName = encodeURI(images[random]);
$('body').css('background-image', 'url(' + safeName + ')');
last = random;
}, time);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment