my goal is to replace one random image from open website with some random image from my list of images. I have this code, but It changes all the images on the website, I need just one random not all of them. Can you help me please with it?
//Handles all images on page with an interval of time
handleImages: function (lstImgs, time) {
$.each($('img'), function (i, item) {
//Skip if image is already replaced
if ($.inArray($(item).attr('src'), lstImgs) == -1) {
var h = $(item).height();
var w = $(item).width();
//If image loaded
if (h > 0 && w > 0) {
self.handleImg(item, lstImgs);
}
else {
//Replace when loaded
$(item).load(function () {
//Prevent 'infinite' loop
if ($.inArray($(item).attr('src'), lstImgs) == -1) {
self.handleImg(item, lstImgs);
}
});
}
}
});
//Keep replacing
if (time > 0) {
setTimeout(function () { self.handleImages(lstImgs, time); }, time);
}
},
//Replace one image
handleImg: function (item, lstImgs) {
$(item).error(function () {
//Handle broken imgs
self.handleBrokenImg(item, lstImgs);
});
self.setRandomImg(item, lstImgs);
},
//Set a random image from lstImgs to item
setRandomImg: function (item, lstImgs) {
var h = $(item).height();
var w = $(item).width();
$(item).css('width', w + 'px').css('height', h + 'px');
$(item).attr('src', lstImgs[Math.floor(Math.random() * lstImgs.length)]);
},
//Removed broken image from lstImgs, run handleImg on item
handleBrokenImg: function (item, lstImgs) {
var brokenImg = $(item).attr('src');
var index = lstImgs.indexOf(brokenImg);
if (index > -1) {
lstImgs.splice(index, 1);
}
self.setRandomImg(item, lstImgs);
},
};
//Run on jQuery ready
$(function () {
self.handleImages(self.gitmbImgs, 3000);
});
//Set global variable
$.gitmb = self;
Aucun commentaire:
Enregistrer un commentaire