Random multiple images javascript - 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]);
});

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!

How to convert HTMLCollection to string

I'am working on a bot that will edit some form on website, one part of the form is where is some html. I copy data from the converting to HTMLCollection do some actions, and then i want to save it back to the . And in case to do so i need to convert HTMLCollection object back to a string.
How i get and convert the data:
var htmlFromTextArea = document.getElementById('nameOfTextArea').value;
var htmlObject = document.createElement('div');
htmlObject.innerHTML = htmlFromTextArea;
var htmlElements = htmlObject.getElementsByTagName("*")
And now i need htmlElements to become string again
I tried the following but it seems not working:
var stringWithHtmlTobeSavedInTextArea = htmlElements.text;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.textContent;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.innerText;
Yes, htmlElements is HTMLCollection. So seperate each element and add outerHTML of element to string using loop.
var htmlObject = document.createElement('div');
htmlObject.innerHTML = "<a>anchor</a><p>paragraph</p>";
var htmlElements = htmlObject.getElementsByTagName("*");
var stringWithHtmlTobeSavedInTextArea="";
for (i = 0; i < htmlElements.length ; i++){
stringWithHtmlTobeSavedInTextArea += htmlElements[i].outerHTML;
}
console.log(stringWithHtmlTobeSavedInTextArea);
Please note that, above solution is not correctly working in case if the HTML inside div element is like <div><a>anchor</a></div>
So It is better to use innerHTML or get actual text from <textarea> eg.
var stringWithHtmlTobeSavedInTextArea = htmlObject.innerHTML;
//Or
var stringWithHtmlTobeSavedInTextArea = htmlFromTextArea;

Array is not an array anymore after getting stringified and parsed (JSON)

After that I stringified my array I parsed it, I then tried to acces one of the elements inside the array (array[number]) but it seems that the elements in the array are all mashed as one or something like that. I would like to know why and how to change this. Thanks in advance!
var linkrecup = localStorage.getItem('linksstring');
JSON.parse(linkrecup);
alert(linkrecup);
var linkarr = [''+linkrecup+''];
alert(linkarr.length); // this gives '1'
var div = document.createElement('div');
document.body.appendChild(div);
div.id = 'placememe'+memenumber+'';
div.className = 'meme';
var nombrememes = document.getElementsByClassName("meme").length;
alert(nombrememes);
var crpt = nombrememes - 1;
alert(crpt);
alert(linkarr[3]); // this gives 'undefined'
Every var that is used is declared in another piece of code, if you want it just ask and I'll gladly give it to you.
EDIT: So basically what im doing (trying) with this code to do is to push a link that is given by the user (prompt) and add it to the array of links that already have some links stored in (.push) then stock it (the whole array) in localStorage (stringified with JSON.stringify) then re-acces this array later (with a localStorage.getItem) then parse it (JSON.parse) and then use one of the elements of the array (link) as the link for an image. Here's the code with the stringify and shit.
var newmeme = prompt('Please paste the link of the meme below!');
memes.push ('placememe'+memenumber+'');
links.push (newmeme);
var div = document.createElement('div');
document.body.appendChild(div);
div.id = 'placememe'+memenumber+'';
div.className = 'meme';
var nombrememes = document.getElementsByClassName("meme").length;
var vrb = nombrememes - 1;
div.innerHTML = '<img src="'+links[vrb]+'" width="700" height="700" alt="" />';
var linksstring = links
localStorage.setItem('linksstring',JSON.stringify(linksstring));
var linkrecup = localStorage.getItem('linksstring');
JSON.parse(linkrecup);
alert(linkrecup);
JSON.parse(object) returns a parsed object
Try using
var parsedlinkrecup=JSON.parse(linkrecup)

Can set name in multiple array

Have a litle problem here with multiple array in Javascript.
I define the array like this: var list = [];
In html I have <img class="Img" id="2" src="/test.png"/>
My goal is to make a multiple array like this on "onload":
list[2][test.png]
Where 2 is the id tag, and the other is the image. In that way I later can do a loop and collect all photos belonging to list[2] or list[3] is that ID exist.
But my problem is, I can't get this to work. I tried this:
var images = document.getElementsByClassName("Img");
for(var i=images.length; i--;) {
var PhotoId = images[i].getAttribute('id'), // Id on the photo
image = images[i].getAttribute('src'); // The images
}
If I now in the loop this.list.push(image) it work like a charm, but that is one-dimensional.
How can I use this PhotoId as I explained above?
in single line u can also do it as, check if list[photoId] array already exists, if yes then push the image into it otherwise create an empty array.
list[photoId] ? list[photoId].push(image) : (list[photoId] = []).push(image);
Try this,
var images = document.getElementsByClassName("Img");
var arr=[];// array
for(var i=images.length; i--;) {
var PhotoId = images[i].getAttribute('id'), // Id on the photo
image = images[i].getAttribute('src'); // The images
arr[PhotoId]=image;
}
console.log(arr);
You can use
this.list[photoId] = []
then
this.list[photoId].push(image)
On another note id should be unique in DOM. If you want to group elements with certain property then use class attribute.

randomize selection and output variable to span tag in javascript

I have this javascript code:
var doNewPoll = function(){
var vacationIndex = Math.round(Math.random(myVacations.length));
var dest1 = myVacations[vacationIndex];
var dest2 = myVacations[vacationIndex];
alert(dest1);
alert(dest2);
}
My 2 questions are:
1) How do I make sure my variables dest1 and dest2 are not the same? I want it to pull 2 different options from the myVacations array.
and 2) I can get the alerts to work, but instead of an alert, I want the results for dest1 and dest2 to appear in the document in span tags id'd Span1 and Span2. I'm just having a brain fart on how to do that.
Thanks!
First, use floor, not round, you don't want your index to be the length :
Math.floor(Math.random(myVacations.length));
Then, the easiest to avoid duplicate is just to loop until the second number is different from the first. This means you must build another index, of course :
var index1 = Math.floor(Math.random(myVacations.length));
var index2 = index1;
while (index2==index1) index2 = Math.floor(Math.random(myVacations.length));
var dest1 = myVacations[index1];
var dest2 = myVacations[index2];
To make the document appear in span, the simplest is to start with the elements yet present :
<span id=d1></span>
<span id=d2></span>
And then to fill them :
document.getElementById("d1").innerHTML = dest1;
document.getElementById("d2").innerHTML = dest2;
// I assume span1 and span2 are the id of those elements
var doNewPoll = function(myVacations, span1, span2){
var vacationIndex1 = Math.round(Math.random(myVacations.length));
var vacationIndex2 = null;
do{
vacationIndex2 = Math.round(Math.random(myVacations.length));
} while (vacationIndex2 == vacationIndex);
document.getElementById(span1).innerHTML = myVacations[vacationIndex1];
document.getElementById(span2).innerHTML = myVacations[vacationIndex2];
}

Categories