Display image based on user selection in two-level cascading dropdown javascript - 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!

Related

How to use a same image multiple times by loading it only once when I need different id for every element

I am a newbie to programming and web developing. The project I am doing is only for practice, if my approach seems ameteur to you, please suggest any better options.
I am trying to develop a parking lot booking system. And in the UI, I want to show all the empty/filled slots (like it is while booking movies or bus tickets).
I couldn't find a top view icon of a car, so I thought of using an image instead of icon.
But as of the image, if I use say 50 images on a single page, the page will get very heavy.
But one important thing is that I need all the elements as seperate entities, only then I will be able to book them with their id(unique address). So I want 50 different divs with seperate distinct ids but want to use only one image for all the slots, or a maximum of 2 different images(keeping the directions in mind).
how to display same image multiple times using same image in javascript
I went through this answer, and found a piece of code that might be useful:
var imgSrc = 'http://lorempixel.com/100/100';
function generateImage() {
var img = document.createElement('img')
img.src = imgSrc;
return img;
}
for (var i = 0; i < 20; i++ ) {
document.body.appendChild(generateImage());
}
While I can make use of a function and a loop in javascript to create as many copies of one image, I don't know how to alot them to the different div tags with distinct ids.
use a function :)
const addMessage = (element, msg, cls) => {
const patt = new RegExp("<");
const messageElement = document.createElement("div");
if (patt.test(msg)) {
messageElement.innerHTML = msg
} else messageElement.textContent = msg;
if (cls) messageElement.classList.add(cls);
element.appendChild(messageElement);
}
const imgPath = "/somepath";
const body = document.querySelector("body");
addMessage(body, `<img src=${imgPath} class="whatever">`, "img1"); //creates new divs with classes. the 3rd arg is optional
the best approach for this is the client side already receiving all this content as a string but as it made clear that it is for study I deduce that it is not the intention to use back end to solve this problem
let allContent = '';
for (var i = 0; i < 20; i++ ) {
allContent += `<div class="wrapper-image"><img src="/path"></div>`
}
document.getElementById('idWrapper').innerHTML = allContent;
speaking in performace the browser will only download the image once, so you can use it as many times as you like, which is disruptive to the changes you make in the DOM (remove, add or edit a content)
In my example you create all the content to be displayed on the page and then add it in a single time, it is not too bad if it is performace but the ideal is to do it on the back side
in the DIV you can put an image address of a variable to do some logical type this:
let allContent = '';
let imgOne = '/oneimg';
let imgOne = '/twoImg';
for (var i = 0; i < 20; i++ ) {
if(i>10){
allContent += `<div class="wrapper-image"><img src="${imgOne}"></div>`
}else {
allContent += `<div class="wrapper-image"><img src="${twoImg}"></div>`
}
}
document.getElementById('idWrapper').innerHTML = allContent;

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
}
}

Use Selected Options Value in For Loop

Good afternoon.
I am trying to use the selected value in the options box in a for loop.
The theory being that if the user selects 3, for example, Javascript will populate 3 boxes with a fruit from the array.
Can anyone point me in the right direction? I have enclosed Codepen link too.
function changeText(){
var e = document.getElementById('selectbox');
var strUser = e.options[e.selectedIndex].value;
for (var i=0; i<=strUser; i++) {
document.getElementById('boldStuff').innerHTML = randomFruit + strUser;
}
}
http://codepen.io/jameswinfield/pen/aNWRKm
The ID element should be unique to the entire dom. You are using it multiple times for boldStuff. If you would like to be able to grab them like that you should use a class.
Here is a version that should do what you want: http://codepen.io/anon/pen/KzmGLP?editors=0010
Keep in mind that sets the value to every box, even the hidden ones. You will have to get a new random fruit per box or they will all have the same fruit.
I changed all id="boldStuff" to class="boldStuff",
grabbed all boldStuffs
var boldStuffs = document.getElementsByClassName('boldStuff');
and looped over every boldStuff
for (var i = 0; i < boldStuffs.length; i += 1) {
//And set the value of each boldStuff to a new random fruit.
boldStuffs[i].innerHTML = getRandomItem(fruitsArray);
}
The following line also only runs once so no matter how many boxes there are they will all have the same fruit (because randomFruit is never changed)
var randomFruit = fruitsArray[Math.floor(Math.random() * fruitsArray.length)];
You can use a function to grab a random fruit instead, something like this:
function getRandomItem(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
Then use getRandomItem(fruitsArray); to get a random fruit.

Random multiple images javascript

I want to change multiple image random on my website.
This code work only for 1 image.
var image = new Array ();
image[0] = "images/pic01.jpg";
image[1] = "images/pic02.jpg";
image[2] = "images/pic03.jpg";
image[3] = "images/pic04.jpg";
image[4] = "images/pic05.jpg";
var size = image.length
var x = Math.floor(size*Math.random())
$('#random').attr('src',image[x]);
If I understood correctly, you will need to select multiple elements instead of just one $('#random') so use the class selector, not ID. And if you use jQuery, you can use each to iterate through the elements, like so:
$('.random').each(function(){
var x = Math.floor(size*Math.random());
$(this).attr('src',image[x]);
});

How to go forward and back through an array?

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;
};
}

Categories