I'm trying to shuffle 3 arrays (not together), to create a jigsaw puzzle. Information inside var cells is from when I define each piece etc in my HTML code. When I reload the page, I need one of the three arrays to appear, and need the contents to be in a random order. Splicing isn't getting me anywhere... I sometimes have all the puzzle piece elements, and sometimes one is missing (I know, I know, splicing removes). Any ideas?
var cells = ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11", "c12",];
var imageSet1 = ["./images1/img1-1.jpg", "./images1/img1-2.jpg", "./images1/img1-3.jpg", "./images1/img1-4.jpg", "./images1/img1-5.jpg", "./images1/img1-6.jpg", "./images1/img1-7.jpg", "./images1/img1-8.jpg", "./images1/img1-9.jpg", "./images1/img1-10.jpg", "./images1/img1-11.jpg", "./images1/img1-12.jpg"];
var imageSet2 = ["./images2/img2-1.jpg", "./images2/img2-2.jpg", "./images2/img2-3.jpg", "./images2/img2-4.jpg", "./images2/img2-5.jpg", "./images2/img2-6.jpg", "./images2/img2-7.jpg", "./images2/img2-8.jpg", "./images2/img2-9.jpg", "./images2/img2-10.jpg", "./images2/img2-11.jpg", "./images2/img2-12.jpg"];
var imageSet3 = ["./images3/img3-1.jpg", "./images3/img3-2.jpg", "./images3/img3-3.jpg", "./images3/img3-4.jpg", "./images3/img3-5.jpg", "./images3/img3-6.jpg", "./images3/img3-7.jpg", "./images3/img3-8.jpg", "./images3/img3-9.jpg", "./images3/img3-10.jpg", "./images3/img3-11.jpg", "./images3/img3-12.jpg"];
var imgSet = [imageSet1, imageSet2, imageSet3];
var imgShuffed = imgSet[Math.floor(Math.random() * imgSet.length)];
for (c in cells) {
var index = Math.floor(Math.random() * imgSet.length);
document.getElementById(cells[c]).src = imgShuffed[index];
imgShuffed.splice(index,1);
}
Break the problem down into parts. First of all, lets see about shuffling an array.
The simplest way I can think of to shuffle an array is to keep picking random elements until all of the elements are gone:
function shuffleArray(arr) {
var newarray = [];
while(arr.length > 0) {
var chosenIndex = Math.floor(Math.random() * arr.length); //choose a number thats in the array
var chosenValue = arr[chosenIndex];
newarray.push(chosenValue); //add the new value to the array
arr.splice(chosenIndex, 1); //and "remove" it from the old array by creating a new array without it
}
return newarray;
}
console.log(shuffleArray([1,2,3,4,5])); //example
Next, choose the correct puzzle as you're doing.
var imgSet = [imageSet1, imageSet2, imageSet3];
var chosenSet = imgSet[Math.floor(Math.random()*imgSet.length)];
Then shuffle the chosen set:
var shuffledChosenSet = shuffleArray(chosenSet);
Now, use that shuffled set to finish the job.
What if you'll use a random number as index to fetch image data, and by that assemble new shuffled array?
Of corse you need to check duplications - but you can make it by saving fetched indexes and comparing the new one with them. Am I getting your problem?
This is you made an array but has two dimensions. For using random function you have merge all your array in an one dimenson array. I hope it helps
var sampleArray = [1,2,3,4,5];
var arrayTemp = [];
for (var i = sampleArray.length;i>=0;i--){
var temp = Rand100()%i;
arrayTemp.push(sampleArray[temp]);
sampleArray.splice(temp,1);
};
console.log(arrayTemp);
Above example gives you an array with random entries of the previous one.This gives you random entries without any duplicate entry and within constant time complexity.
Here is the demo : http://jsfiddle.net/patelmit69/tjmvqajL/
var cells = ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11", "c12",];
var indexes = new Array();
var imageSet1 = ["http://dummyimage.com/100x100/000/fff&text=img11", "http://dummyimage.com/100x100/000/fff&text=img1-2.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-3.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-4.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-5.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-6.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-7.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-8.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-9.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-10.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-11.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-12.jpg"];
var imageSet2 = ["http://dummyimage.com/100x100/000/fff&text=img11", "http://dummyimage.com/100x100/000/fff&text=img2-2.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-3.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-4.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-5.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-6.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-7.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-8.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-9.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-10.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-11.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-12.jpg"];
var imageSet3 = ["http://dummyimage.com/100x100/000/fff&text=img11", "http://dummyimage.com/100x100/000/fff&text=img3-2.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-3.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-4.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-5.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-6.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-7.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-8.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-9.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-10.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-11.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-12.jpg"];
var imgSet = [imageSet1, imageSet2, imageSet3];
alert(imgSet.length);
var imgShuffed = imgSet[Math.floor(Math.random() * imgSet.length)];
for (c in cells) {
var index = Math.floor(Math.random() * imgShuffed.length);
document.getElementById(cells[c]).src = imgShuffed[index];
imgShuffed.splice(index,1);
}
<img id="c1" src='' />
<img id="c2" src='' />
<img id="c3" src='' />
<img id="c4" src='' />
<img id="c5" src='' />
<img id="c6" src='' />
<img id="c7" src='' />
<img id="c8" src='' />
<img id="c9" src='' />
<img id="c10" src='' />
<img id="c11" src='' />
<img id="c12" src='' />
Related
On my website I'm displaying an image which i styled with css to be a card. With a hover effect you can flip the card (frontside is the image) and read an image description on the back side. Further I added a button "Shuffle" which replaces the image with a new one selected random out of an array.
My problem: If the new image is selected, the image description of course stays the same. Is it somehow possible to not only connect the image to an array value but also the fitting text for the description as every image needs an individual description? (Code at the bottom)
Thanks!
<body>
<div class="maincontainer">
<div class="thecard">
<div class="thefront">
<img src="images/meme1.jpg" id="picture1"/>
</div>
<div class="theback">Picture1 Description</div>
</div>
</div>
<button onClick="shuffle();">SHUFFLE</button>
<script type="text/javascript">
function shuffle(){
var images1 = [],
index1 = 0;
images1[0] = "images/meme2.jpg";
images1[1] = "images/meme3.jpg";
images1[2] = "images/meme4.jpg";
index1 = Math.floor(Math.random() * images1.length);
document.getElementById("picture1").src = images1[index1];
}
</script>
</body>
Instead of just storing the image URL in an array, store the URL and the description in objects and put the objects into an array:
function shuffle(){
var images1 = [];
images1.push({url:"images/meme1.jpg", description: "meme 1"});
images1.push({url:"images/meme2.jpg", description: "meme 2"});
images1.push({url:"images/meme3.jpg", description: "meme 3"});
images1.push({url:"images/meme4.jpg", description: "meme 4"});
images1.push({url:"images/meme5.jpg", description: "meme 5"});
var index1 = Math.floor(Math.random() * images1.length);
console.log(images1[index1].url, images1[index1].description);
}
shuffle();
shuffle();
shuffle();
shuffle();
shuffle();
shuffle();
Instead of storing only the images, you can store the description too. In this case you need to make an array of objects: this is how it is supposed to look like:
let images = [
{
src: './image.png', //source of the image
description: 'This is an image' //Description of the image
}
]
Then shuffle this array just like you shuffled the old array.
function shuffle(){
var images1 = [], descriptions = [],
index1 = 0;
images1[0] = "images/meme2.jpg";
images1[1] = "images/meme3.jpg";
images1[2] = "images/meme4.jpg";
descriptions[0] = "Picture2 Description";
descriptions[1] = "Picture3 Description";
descriptions[2] = "Picture4 Description";
index1 = Math.floor(Math.random() * images1.length);
document.getElementById("picture1").src = images1[index1];
document.getElementsByClassName("theback")[0].innerText = descriptions[index1];
}
I have I array of images src ["http://src1", "http://src2", "http://src3"]. I want for get all images from that array and manipulate them, for example placing them into a div?
var imgSrc = ["http://src1,http://src2,http://src3"];
var string = imgSrc[0];
console.log(string);
var array = string.split(",");
console.log(array);
var inHTML = '';
console.log(array[0]);
$.each(array, function(key, value){
var html = '<img src="'+ value[key]+'" align="center">';
inHTML += html;
});
$('div#item').html(inHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item"></div>
You can append the dynamically created Images from the array to a perticular div. Hope this helps...
HTML
<html>
<head>
</head>
<body>
<h1>Images</h1>
<div id="content">
</div>
<script src="app.js"></script>
</body>
</html>
JS
var imageSources = ["http://src1,http://src2,http://src3"]
imageSources.forEach(element => {
var img = document.createElement("img");
img.width = '300';
img.height = '300';
img.src = element;
document.getElementById("content").appendChild(img)
};
I think your array is somewhat like:
["http://src1","http://src2","http://src3"]
If I am right then you can do something like:
var y = x.map((key,value)=>{return ('<div>'+key+'</div>')});
y will be an array with the div tags containing images.
Hope, I understood your problem.
I want for get all images from that array and manipulate them, for
example placing them into a div
You can dynamically generate img elements and add them to a div.
To iterate through the array you could use forEach, creating the img elements within the loop using createElement and appendChild to append the image to the div
See example below, which should get you started.
var images = ["https://placehold.it/50x50","https://placehold.it/25x25","https://placehold.it/75x75"];
var target = document.getElementById('target');
images.forEach(function(imgSrc){
var newImg = document.createElement("img");
newImg.src = imgSrc;
target.appendChild(newImg);
})
<div id="target"></div>
Creating an Array:
You must use the following syntax to to create a JavaScript Array:
var array_name = [ item1, item2, ... ];
Or Using the JavaScript Keyword new:
var array_name = new Array( item1, item2, ... );
So your array must be like this:
var image_source = [ 'http://src1', 'http://src2', 'http://src3' ];
Access the Elements of an Array:
You refer to an array element by referring to the index number. for example this statement accesses the value of the first element in cars:
var first_image = image_source[ 0 ];
Example:
var image_source = [ 'http://img1', 'http://img2', 'http://img3' ];
document.getElementById( 'demo' ).innerHTML = image_source[ 1 ];
<div id="demo"></div>
I have a question concerning pictures in an array. I am able to change the picture with a click, but only once. This is my code with some example pictures. There are a lot of tutorials on the net but maybe too complex for me so I created a simple thing.
<html>
<head>
<script type="text/javascript">
//here I am creating my array
var myPicture = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
]
// this should be the function and I think here is the error
function nextPic() {
myPicture[1] = document.images;
}
</script>
</head>
<body>
<img src="http://www.java2s.com/style/download.png" width="107" height="98" />
<form>
<input type="button" onclick="nextPic()" value="Change image">
</form>
</body>
</html>
The simple question is, what do I have to change in my code to show the second, third, x pic with one click. Or is there an simple jQuery function for it?
Here's a working example: http://jsbin.com/dubuhizucu/edit?html,console,output
so a couple of things..
1) you need a variable to keep track of where you are in your pictures array.
2) on click, increment that variable from step 1. then, check if it's bigger than the length of your pictures array. if it is then we need to reset it back to 0.
3) simply set the src attribute on the image to the URL from your pictures array, setting the index to whatever the value of counter is!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="http://www.java2s.com/style/download.png" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />
<script>
var target = document.getElementById('target');
var counter = 0;
var myPictures = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
];
function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
</script>
</body>
</html>
Give your img an id: id="img1"
Create a global variable, for example:
var x = 0;
A global variable is declared in the scope of the entire file, meaning it is not surrounded by any functions, loops, if statements, etc. Your array, myPicture is global.
Then in your function:
function nextPic()
Write instead:
function nextPic(){
// Increment x by 1, x = x + 1
x++;
// Check if on last element of array, change x to first
if(x >= myPicture.length) {
x = 0;
}
// Use variable, declared as number, to access img in array
document.getElementById("img1").src = myPicture[x];
}
If we do not check if x is greater than or equal to the array length then once we have iterated through each image we would attempt to access a null value of the array, one that does not exist.
Your example has an array length of 3, therefore it has indices 0-2. We cannot access any index greater than 2, therefore we set x back to 0.
Your nextPic function is a little bit backwards.
Each time nextPic is called, you're setting the second element in your myPicture array equal to document.images. That's not what you want. You want to set the src of the image (document.images[0]) equal to the next image URL, so you need a way to keep track of what image you're working with (currentImageIndex).
Here's a working example:
var myPicture = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
];
var currentImageIndex = 0;
function nextPic() {
currentImageIndex = (currentImageIndex + 1) % myPicture.length;
document.images[0].src = myPicture[currentImageIndex];
}
<img src="http://www.java2s.com/style/download.png" width="107" height="98" />
<form>
<input type="button" onclick="nextPic()" value="Change image">
</form>
I know there are already a few questions like this, but I just can't seem to apply any of the answers (this is my first time making anything like this at all). I currently have a page that, when a button is pushed, a random image appears (thanks to some of the great posts on here, this is actually working). My issue is, the random number has a lot of repeats prior all the images being seen. I am wanting to make it where all images are seen (in a random order) before any duplicates. This is what is in the body:
<form name="imageForm">
<table border=3>
<tr align="center">
<td>
<input onclick="displayImage();" type=button value="Click Here">
</td>
</tr>
<tr>
<td>
<img src="blank.jpg" name="canvas" />
</td>
</tr>
</table>
</form>
Here is the script:
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
}
</script>
From what I have read, the way to do this would be to add a spice, and have shown images dropped into a new array, then once the original array equals 0, then have it reset. Try as I might, I have not been able to successfully integrate that into my code :( . This is what I ended up with (which does nothing, and breaks the function entirely):
<script>
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var shownImages = []
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
shownImages.unshift(imagesArray.splice(num,num+1));
if(images.length == 0){
images.Array = shownImages;
shownImages = [];
return shownImages[0];
}
</script>
Another method mentioned seemed to be to have a function that shuffled the images first, then displayed them in the shuffled order, then reshuffled and repeated, but I got even less far with that.
There also seems to be some question on whether the random number max should be imagesArray.length by itself, or +1 or -1. I am sure there are a number of other issues with this as well, but like I said, this is my first attempt. Any help is appreciated.
You should keep track of the numbers that you have generated, and if its a repeat then get a new number.
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
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();
}
}
</script>
Here's my code (what I'm stuck on is after the jump)
<script language="JavaScript" type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var countThisMany = 4; //how many data-id's I want to count per "section" of images
var finalString = ""; //blank var to be used later, must be defined here.
</script>
<img src="foo.jpg" data-id="id1" data-item="1" /> // just a bunch
<img src="foo.jpg" data-id="id2" data-item="2" /> // of images with
<img src="foo.jpg" data-id="id3" data-item="3" /> // data-* usage to
<img src="foo.jpg" data-id="id4" data-item="4" /> // store two bits
<img src="foo.jpg" data-id="id5" data-item="5" /> // of information
<img src="foo.jpg" data-id="id6" data-item="6" /> // that I'll need
<img src="foo.jpg" data-id="id7" data-item="7" /> // to extract
<img src="foo.jpg" data-id="id8" data-item="8" /> // later on below.
<img src="bar.jpg" data-id="id9" data-item="1" /> // another set of images
<img src="bar.jpg" data-id="id10" data-item="2" />
<img src="bar.jpg" data-id="id11" data-item="3" />
<img src="bar.jpg" data-id="id12" data-item="4" />
<img src="bar.jpg" data-id="id13" data-item="5" />
<img src="bar.jpg" data-id="id14" data-item="6" />
<img src="bar.jpg" data-id="id15" data-item="7" />
<img src="bar.jpg" data-id="id16" data-item="8" />
<script type="text/javascript">
var item_array = $("img").map(function() {
return $(this).attr("data-item");
}).get();
//alert(item_array);
//returns "1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8"
var id_array = $("img").map(function() {
return $(this).attr("data-id");
}).get();
//alert(id_array);
//returns "id1,id2,id3,id4,id5,id6,id7,id8,id9,id10,id11,id12,id13,id14,id15,id16"
for (i=0;i<countThisMany;i++){
finalString=finalString+id_array[i]+';';
}
//alert(finalString);
//returns "id1;id2;id3;id4" -- could be more or less if "countThisMany" is changed to something other than 4
</script>
This entire code is self-contained so feel free to save it as an HTML and uncomment the alerts to see the results.
What I need, however, is a step further. I would like to only collect the data-id of the img tags whose data-item are less than or equal to the variable countThisMany
So the end result of finalString would be "id1;id2;id3;id4;id9;id10;id11;id12". And if countThisMany was changed to 2, for instance, it would be "id1;id2;id9;id10"
I feel as though I am so close but I can't figure out how to only gather the first 4 of the first set of 8 images, and the first 4 of the second set of 8 images. Again, the total amount of images and how many I would need to capture vary, hence the "countThisMany' var.
This is my first post to the amazing stackoverflow community, so I'm excited! Thanks to all contributors ahead of time!
Use filter method
var item_array = $("img").filter(function() {
return parseInt($(this).data("item")) <= countThisMany;
}).map(function() {
return $(this).data('id');
}).get();
var countThisMany = 4;
var item_array = $("img")
.filter(function() {
return parseFloat( $(this).attr("data-item") ) <= countThisMany;
})
.map(function() {
return $(this).attr("data-id");
})
.toArray(); /* instead of get() */
Note that this will return an array. You seem to want a string, so you might want to call .join(',') on the result.
Use $.grep in combination with $.map. I also added a join to array rather than the loop. fiddle: http://jsfiddle.net/brentmn/5yNbE/5/
var countThisMany = 2;
var finalString = "";
var id_array = $.grep($('img'), function(item) {
return ($(item).data('item') <= countThisMany);
}).map(function(item) {
return $(item).data('id')
});
finalString = id_array.join(';');