How to go forward and back through an array? - javascript

I've got an array / object like below:
{
“Food’ : [{‘ImagesId”: ”38”, ”ImagesPath”: ”url”, ”Tag”: ”Food”}],
“Sport’: [{‘ImagesId”: ”64”, ”ImagesPath”: ”url”, ”Tag”: ”Sport”}]
}
I want to be able to display one image at a time and have buttons to go forward and back through the images. I need to have a variable that describes the currently viewed image.
Below is what I currently have and it allows me move forward through the array but not back. I just want a simple function that randomises the array above displays one image at a time and allowing the user to move forward and back through the images.
Finally I need something like window.currentlyShown
function receivedData(data) {
function changeOfferPicture() {
if (window.currentlyShownOffer) {
var tagArray = data[window.currentlyShownOffer.Tag];
tagArray.splice(tagArray.indexOf(currentlyShownOffer), 1);
//alert(window.currentlyShownOffer.ImagesId);
}
var tags = Object.keys(data);
var randomTag = tags[Math.floor(Math.random() * tags.length)];
var tagArray = data[randomTag];
window.currentlyShownOffer = tagArray[Math.floor(Math.random() * tagArray.length)];
window.shownCache.push(window.currentlyShownOffer);
document.getElementById('top5').src = window.currentlyShownOffer.ImagesPath;
};
}

Related

Display image based on user selection in two-level cascading dropdown javascript

So, I have two cascading dropdowns, both displaying different images based on user selection. But now I need to restrict the number of images in the second dropdown based on the first dropdown value.
This is an example of how I did that with fonts: https://jsfiddle.net/gjq8ov1h/
But now, I want to do this with images, but I don't even know where to begin.
fyi, I have the first set of images in order like pic1.jpg, pic2.jpg, but the second set is numbered based on its dimensions. i can change rename them with num1, num2, etc. if needed.
I used these both functions to get the images:
var imageList = Array();
for (var i = 1; i <= 8; i++) {
imageList[i] = new Image();
imageList[i].src = "Images/image"+i+".jpg";
}
function switchImage() {
var selectedImage = document.myForm.switch.options[document.myForm.switch.selectedIndex].value;
document.myImage.src = imageList[selectedImage].src;
}
And this for the second one:
function swapImage(){
var image = document.getElementById("imageToSwap");
var dropd = document.getElementById("dlist");
image.src = dropd.value;
}
I really can't seem to figure it out. Would appreciate any help!

Why is altered value being written to original array onclick

i want to pull data from a .csv file and pass this data to a function to format every row of the .csv file to be a single object. These objects are then stored in an array called "list". So far so good. This is all working.
Next i want a button that calls a function onclick called "roll" that takes a random index from the "list" array and saves an instance of the random oject in a temporarily variable called randomItem.
Then i want to check certain properties of randomItem for specific values and if a certain condition is met it should change a specific property called "randomItem.Name". Finally i want the altered "randomItem" to be pushed into a new array called "results". These results are then being displayed on the website.
If I change the propertys value with "randomItem.Name = randomItem.Name + 'someString'" it also overwrites the original object in the "list" array. I dont want it to do this as i want to repeat the process of rolling random objects from this list several times. Therefor i need the "list" array to keep its original state. I cant get my head around why it overwrites the any list.
html
<button id="btnItem1">Roll</button>
js
$(document).ready(function() {
let list = [];
let results = [];
$('#btnItem1').click({slotName:'item1', listName:list, index:0}, roll);
// i need to pass slotName, listName and index because i have several buttons and list in the real project
getData('data.csv').then(data => formatData(data)); // get data from csv files
async function getData(url) {
const response = await fetch(url);
const data = await response.text();
return data;
};
function formatData(data) { // real formatting function taken out for stackflow
let formatted = // some formatting stuff;
list.push(formatted);
};
function roll(options) {
const slot = options.data.slotName;
const listTemp = options.data.listName;
const index = options.data.index;
if (slot.includes('item')) { // real criteria taken out for stackflow
do {
const randomNumber = Math.floor(Math.random() * (listTemp.length - 1) + 1);
let randomItem = listTemp[randomNumber];
if (1 == 1) { // real criteria taken out for stackflow
let chance = Math.round(Math.random());
if (chance) {
randomItem.Name += '(altered)';
}
}
results.splice(index, 1, randomItem);
} while (1 != 1); // real criteria taken out for stackflow
};
};
});
I expect it to write the altered "randomItem.Name" only to randomItem itself. Not even to listTemp but definitly not to the global "list". Do you have any idea why it is doing this and how i can prevent this? How can i get the object into randomItem without randomItem keeping its reference to any list. Thank you guys in advance!

Random image arrays for Javascript

I'm new with Javascript, and coding in general. I have been trying to create a code that has an array full of images. Then, when a button is clicked, it will generate a number that links in with the array, and then display the image. Furthermore, I want it to then not use that number/image again until all are used up.
For now I am just starting with having an array, randomly generating a number and displaying the image. I have scoured this forum, gone on SEVERAL posts and tried numerous codes. This is the closest I have got to working.
var imagesArray = [
"1.jpg", "2.jpg", "3.png", "4.png",
"5.png", "6.jpg", "7.jpg", "8.png"
];
function displayImage() {
var rand = imagesArray[Math.floor(Math.random() * 8)
document.canvas.src = imagesArray[rand];
}
With this code, I am getting an "Unexpected token: document" error. I don't even know if the other parts work, they just aren't erroring.
Where am I going wrong?
This code satisfies the requirement of cyclic uniqueness.
var imagesArray = [...]; // initial array
var imagesArrayTemp = imagesArray.slice(0); // clone of initial array
function displayImage() {
var index = Math.floor(Math.random() * imagesArrayTemp.length);
document.canvas.src = imagesArrayTemp[index];
imagesArrayTemp.splice(index, 1); // remove just displayed item
if(!imagesArrayTemp.length) {
console.log('All images have been displayed');
imagesArrayTemp = imagesArray.slice(0); // clone again, let's do a cycle
}
}

How can I find a random number not located in an array? Want to loop through random numbers until one is found

I have a folder containing 10 images (img-1.jpg, img-2.jpg, ...). I currently feature 6 images on a site and I am trying to randomly swap out one of the 6 images with a different one that is not already shown on the page.
I have an array of all of my images (fullList), then I generate and array of the images that are currently shown (currentList).
Where I am having an issue is looping through the currentList array until I find a randomly generated item that is not currently in the currentList array. Then I will chose a random image from the page and change the image.
What I have now:
function sawpHeadshots() {
var fullList = [1,2,3,4,5,6,7,8,9,10];
var currentList = [];
$('#headshots li').each(function() {
currentList.push(parseInt($(this).css('background-image').replace(/\D+/, '')));
});
function generateRandom() {
return fullList[Math.floor(Math.random() * fullList.length)];
}
var rand = generateRandom();
/* not sure how to proceed at this point. */
}
Create a copy of the array randomly sort it, and remove them from the array when you create it. No need to keep generating random numbers or keeping track what was used.
var fullList = [1,2,3,4,5,6,7,8,9,10];
var random = fullList.slice(0).sort(function() {
return .5 - Math.random();
});
//get value with pop()
var current = random.pop();

I want a random homepage (from a predefined list) to show up when I click a link

I want a random homepage (from a predefined list) to show up when I click a link. And really this is Two questions so question one, is it possible? If yes then how?
What if the file are in different folders?
Would the code then look like this?
var arrPages = [ 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/feyra/feyra.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/rayne/rayne.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/adrienna/adrienna.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/averya/aveyra.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/demaen/demaen.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/phoenyx/phoenyx.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/raven/raven.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/trysten/trysten.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/xiandre/xiandre.html'];
document.getElementById('13').onclick = function () {
var randUrl = arrPages[Math.floor(Math.random() * arrPages.length)];
// Redirect/popup/new tab
window.open(randUrl,'test');
}
// A predefined list of pages
var arrPages =
[
'http://google.com',
'http://yahoo.com',
'http://xtra.co.nz',
'http://asdf.com'
];
// Get the element
var aLink = document.getElementById('aLink');
// Bind the click event of aLink
aLink.onclick = function () {
// Get an integer that'll determine the index of arrPages to access
var randomInt = Math.floor(Math.random() * arrPages.length);
// Get the element with an index of randomInt
var randUrl = arrPages[randomInt];
// Here you can do whatever you like with randUrl, in this case
// we'll open a new window that'll point to randUrl
// e.g. http://xtra.co.nz
window.open(randUrl, 'test');
}
For an explanation of the functions used to set randomInt
see Explain Math.floor(Math.random())

Categories