Hi I found a script which loads images one after another into my div element. Everything works fine, but I would like it to load random images which do not repeat in a circle of all images.length.
Since I'm a total newb in this I tried to do something but most of the time I am able to load random images but without repeat check.
If you can, please help.
Thank you all in advance!
<script src="js_vrt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
//Initial Background image setup
image.css('background-image', 'url(' + images[i++] + ')');
//Change image at regular intervals
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1500);
});
if (i == images.length)
i = 0;
}, 5000);
});
</script>
You can use the shuffle method explained on the answer below.
How can I shuffle an array?
And get the first element on your array
image.css('background-image', 'url(' + images[0] + ')');
You may find a issue on this method, when the same image get loaded after shuffle the array. In this case, I recommend you to store in a variable the name of the last image shown, and before the array get shuffled, just test if the first element is equal the last image.
var lastImageLoaded ='';
setInterval(function() {
shuffle(images);
var imageUrl = images[0];
if(lastImageLoaded !== ''){ // Handle the first load
while(lastImageLoaded === images[0]){
shuffle(images);
}
}
lastImageLoaded = image;
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + imageUrl + ')');
image.fadeIn(1500);
});
Here is a complete object that takes in an array of image urls, and then displays them randomly until it has shown them all. The comments should be pretty explanatory, but feel free to ask questions if I didn't explain something enough. Here is a fiddle
//Object using the Revealing Module pattern for private vars and functions
var ImageRotator = (function() {
//holds the array that is passed in
var images;
// new shuffled array
var displayImages;
// The parent container that will hold the image
var image = $("#imageContainer");
// The template image element in the DOM
var displayImg = $(".displayImg");
var interval = null;
//Initialize the rotator. Show the first image then set our interval
function init(imgArr) {
images = imgArr;
// pass in our array and shuffle it randomly. Store this globally so
// that we can access it in the future
displayImages = shuffle(images);
// Grab our last item, and remove it
var firstImage = displayImages.pop();
displayImage(firstImage);
// Remove old image, and show the new one
interval = setInterval(resetAndShow, 5000);
}
// If there are any images left in our shuffled image array then grab the one at the end and remove it.
// If there is an image present in the Dom, then fade out clear our image
// container and show the new image
function resetAndShow() {
// If there are images left in shuffled array...
if (displayImages.length != 0) {
var newImage = displayImages.pop();
if (image.find("#currentImg")) {
$("#currentImg").fadeOut(1500, function() {
// Empty the image container so we don't have multiple images
image.empty();
displayImage(newImage);
});
}
} else {
// If there are no images left in the array then stop executing our interval.
clearInterval(interval);
}
}
// Show the image that has been passed. Set the id so that we can clear it in the future.
function displayImage(newImage) {
//Grab the image template from the DOM. NOTE: this could be stored in the code as well.
var newImg = displayImg;
newImg.attr("src", newImage);
image.append(newImg);
newImg.attr("id", "currentImg");
newImg.fadeIn(1500);
}
// Randomly shuffle an array
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
return {
init: init
}
});
var imgArr = [
"https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg",
"https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg",
"https://i.ytimg.com/vi/icqDxNab3Do/maxresdefault.jpg",
"http://www.funny-animalpictures.com/media/content/items/images/funnycats0017_O.jpg",
"https://i.ytimg.com/vi/OxgKvRvNd5o/maxresdefault.jpg"
]
// Create a new Rotator object
var imageRotator = ImageRotator();
imageRotator.init(imgArr);
you can try to make and array filled with 0's
var points = new Array(0,0,0, 0)
//each one representing the state of each image
//and after that you make the random thing
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
while (points[i]!=1){
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
}
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
points[i]=1;
image.fadeIn(1500);
});
Related
<img src="link" id="hof" </div>
<span id="myspan">Compliment: </span>
<script type="text/javascript">
function change() {
// ---------- Caption and images !! -----------//
var things = ["Slide01", "Slide04", "Slide05", "Slide06"];
var captions = ["Very nice", "Awesome", "Cool", "Best"];
// ^^^^^^^^^^ Captions and Images !! ^^^^^^^^^^ //
var image = document.getElementById('hof');
var thing = things[];
image.src = "link" + thing + ".jpg"; // change the image
span = document.getElementById("myspan");
span.innerText= "Compliment: " + captions[]; //change caption
}
setInterval('change()', 4000);
</script>
So i am new to javascript i am trying to make a slideshow with captions but i need the values in the array to display in sequence like (slide01>slide02>slide03) then repeat from the start when it reaches the last value.
To answer what you actually asked: You'd use an index variable defined outside change. Start with 0 and (after rendering the slide) increment it, wrapping around when you get to things.length. There's a trick for that last part:
index = (index + 1) % things.length;
Other notes:
Don't use parallel arrays, use an array of objects.
var slides = [
{name: "Slide01", caption: "Very Nice"},
// ...
];
then
var slide = slides[index];
image.src = "link" + slide.name + ".jpg";
span.innerText = "Compliment: " + slide.caption + ".jpg";
Define that array outside change, there's no need to re-create it every time change is called.
Don't pass strings into setInterval or setTimeout; pass in the function instead:
setInterval(change, 4000);
Consider wrapping all of your code in a scoping function so index, the array of slides, and the change function aren't globals:
(function() {
// ...your code here...
})();
<body onload="imgcarousel()">
<img src="" id="hof">
<p id="caption"></p>
<button onclick="imgcarousel()">Next</button>
</body>
<script>
var count = 0;
var things = ['Slide01', 'Slide04', 'Slide05', 'Slide06'] ;
var captions = ['Very Nice','Awesome','Cool','Best'];
function imgcarousel()
{
count++;
var img = document.getElementById("hof");
var caption = document.getElementById("caption");
if(count >= things.length)
{
count = 0;
}
img.src = things[count]+".png";
caption.innerHTML = "Compliments: " +captions[count];
}
</script>
I found this code on Stack Overflow: change images on click.
And it works for me. I want it to be random, but how can i prevent it from repeating the images. It should first repeat the images, when the user has clicked through all images.
I have made an JSfiddle with my code: http://jsfiddle.net/gr3f4hp1/
JQuery code:
var images = ["02.jpg","03.jpg","01.jpg"];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
Keep track of the numbers that you have generated, and if its a repeat then get a new number.
You can Work Around This
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
you can try this code .
var images = ["02.jpg","03.jpg","01.jpg"];
var imagecon = [];
$(function() {
$('.change').click(function(e) {
if(images.length == 0) { // if no image left
images = imagecon; // put all used image back
imagecon = []; // empty the container
}
var index = Math.floor(Math.random()*images.length);
var image = images[index];
imagecon.push(image); // add used image
images.splice(index,1); // remove it to images
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
you could add a class to every image that appears like:
image.addClass("viewed")
and write an if statement that show the image only if it hasn't the class viewed:
if(!image.hasClass(viewed)){
(show the image methods);
image.addClass("viewed")
}
I'm not going to make all the code for you, just try this way, learn, fail, success, have fun! :D
Try this image change according to imgCnt variable.
var images = ["01.jpg","02.jpg","03.jpg","01.jpg"];
var imgCnt=1;
$(function() {
$('.change').click(function(e) {
// var image = images[Math.floor(Math.random()*images.length)];
if(imgCnt >= images.length){
imgCnt=0;
}
var image =images[imgCnt];
// alert(image);
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
imgCnt++;
});
});
});
Demo
There are lots of method here i just push the value of visited image in to Visited array
Campate two array show only differ element
var images = ["02.jpg","03.jpg","01.jpg"];
var visited = [];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
visited.push(image);
$('#bg').parent().fadeOut(200, function() {
y = jQuery.grep(images, function(value) {
if(jQuery.inArray(value, visited) == -1){
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
}
});
} });
});
});
I hopes its help
JS:
function getItem() {
var rand = Math.floor((Math.random() * 110) + 1);
Weapon = "Opening..."
document.getElementById("Weapon").innerHTML = Weapon;
if (rand < 3) {
document.getElementById("Weapon").innerHTML = "Item Type One";
} else if (rand > 2 && rand < 5) {
document.getElementById("Weapon").innerHTML = "Item Type Two";
}
// Continues onward etc...
}
HTML:
<button onclick="getItem()">Get Item</button>
<span id="image"><!-- Display an image here? --></span>
You Unboxed: <span id="Weapon">Nothing</span>
I was wondering if it would be possible to also set the source of an image in this HTML from my Javascript code. So if I get "Item One" it will display that image in my HTML?
You just need to create an array containing the paths to your images such as
var images = ["image1.png", "image2.png"]
Then get a reference to your image element, then set its source to the image in the array accordingly
myImage.src = images[0] for example
Edit:
So you said you have an array of images like this
var images = ["stub.png", "Other.png"];
I see that you are using a <span> to display your images. So you need to get a reference to that <span> element.
var myImage = document.getElementById("weapon");
Since you are using a <span> element to display your image, not a <img>, so to show your image, you do this
myImage.style.backroundImage = url(images[n]); with n being the image index corresponding to your if/else. You should use <img> to display your image instead.
There is no image tag and url, how can you display different images, there is no second argument in setTimeout function. Here i can help you
<br/>
You Unboxed: <img id="Weapon" src=''/>
function openCase() {
var Gun = Math.floor((Math.random() * 110) + 1);
console.log(Gun);
var weaponarray = [] // create your image array here
Weapon = //some initial image
document.getElementById("Weapon").src=Weapon;
setInterval(callback,500) // every 500 mili sec call function
}
function callback(){
var Gun = Math.floor((Math.random() * 110) + 1);
if (Gun < 3) {
Weapon = weaponarray[Gun];
document.getElementById("Weapon").src=Weapon;
}
else if (Gun > 2 && Gun < 5) {
Weapon = weaponarray[Gun];
document.getElementById("Weapon").src=Weapon;
}
}
I am a javascript newbie...
I'm trying to write a function that grabs a random image from a directory and sets it as the background image of my banner div. I also need to set the size of the image and for it not to repeat. Here's what I've got so far, and it's not quite working.
What am I missing?
$(function() {
// some other scripts here
function bg() {
var imgCount = 3;
// image directory
var dir = 'http://local.statamic.com/_themes/img/';
// random the images
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
// array of images & file name
var images = new Array();
images[1] = '001.png',
images[2] = '002.png',
images[3] = '003.png',
document.getElementById('banner').style.backgroundImage = "url(' + dir + images[randomCount] + ')";
document.getElementById('banner').style.backgroundRepeat = "no-repeat";
document.getElementById('banner').style.backgroundSize = "388px";
}
}); // end doc ready
I messed around with this for a while, and I came up with this solution. Just make sure you have some content in the "banner" element so that it actually shows up, because just a background won't give size to the element.
function bg() {
var imgCount = 3;
var dir = 'http://local.statamic.com/_themes/img/';
// I changed your random generator
var randomCount = (Math.floor(Math.random() * imgCount));
// I changed your array to the literal notation. The literal notation is preferred.
var images = ['001.png', '002.png', '003.png'];
// I changed this section to just define the style attribute the best way I know how.
document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();
Here's something sort of like what I use, and it works great. First, I rename all my background images "1.jpg" through whatever (ex. "29.jpg" ). Then:
var totalCount = 29;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg';
document.getElementById("div1").style.backgroundSize="100%";
document.getElementById("div1").style.backgroundRepeat="fixed";
}
Then run the function ChangeIt() .
I am trying to set the background images to be fixed and be stretched to fit the screen. the js that i am using if to switch the backgroud image on every pageload
Head
<script language="JavaScript">
<!-- Activate cloaking device
var randnum = Math.random();
var inum = 1;
// Change this number to the number of images you are using.
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "http://simplywallpaper.net/pictures/2010/10/22/how_to_train_your_dragon_monstrous-nightmare.jpg"
images[2] = "tiler3.jpg"
images[3] = "wicker3.jpg"
images[4] = "aaa4.jpg"
// Ensure you have an array item for every image you are using.
var image = images[rand1]
// Deactivate cloaking device -->
</script>
Body
<script language="JavaScript">
<!-- Activate cloaking device
document.write('<body background="' + image + '" text="white" >')
</script>
The js itsself works fine to randomize the images but is currently set to 1 image
Simple, change both scripts to:
<script type="text/javascript">
var images = [ 'http://tinyurl.com/qhhyb8k'
, 'http://tinyurl.com/nqw2t9b'
, 'http://tinyurl.com/nkogvoq'
// , 'url 4'
]
, image = images[ (Math.random() * images.length)|0 ]
; //end vars
window.onload=function(){
document.body.style.background=
"url('"+image+"') no-repeat center center fixed";
document.body.style.backgroundSize=
"cover"; // width% height% | cover | contain
};
</script>
Nothing more to configure, just add/remove/change urls.
Example fiddle here.
Hope this helps.
inum needs to be set to something other than 1. You can set it to the number of images in the array.
Also, arrays start with index 0, so to be safer, you should index your array accordingly.
<script language="JavaScript">
// setup your image array
var images = new Array;
images[0] = "firstImage.jpg";
...
images[4] = "lastImage.jpg";
// alternative image array setup
var images = [ 'firstImage.jpg', 'secondImage.jpg', ... ,'lastImage.jpg' ];
// check to see if the image list is empty (if it's getting built somewhere else)
if (images.length) {
// set inum
var inum = images.length;
var randnum = Math.random();
var randIndex = Math.floor(randnum * inum);
// Ensure you have an array item for every image you are using.
var imageFile;
if (randIndex < images.length) {
imageFile = images[randIndex];
}
...
</script>
In the body
<script type="text/javascript">
window.onload = function() {
if (imageFile) {
var body = document.getElementsByTagName("body")[0];
if (body) { body.setAttribute('style',"background:url('"+imageFile+"'); text: white;"); }
}
}
</script>