//Setting up the Array
var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];
// creating the randomizing
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
// image source looks for the attribute, by using the variable arraying
$('img').attr('src',random);
Above is my code. I currently have javascript set up this way. The current code has the piece where images are randomly replaced from an image from the array. I want to have the code state that switch every image with a new random image, not every image with the same time. I like how it is random every time, but I also want to random for each picture.
Set up a loop to go over each image, pick a random one, and then assign to that one:
var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];
$("img").each(function() {
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
$(this).attr('src',random);
});
You can use a callback function with the attr method to calculate the value for each element:
$('img').attr('src', function(){
return arrayImg[Math.floor(Math.random()*arrayImg.length)];
});
Related
I am trying to make a memory game and I want to give each image an ID so that the program can keep track of which images are the same. My function was working properly and generating the grid of random images but when I try to give the images their respective ID, random images just come out missing. Does anyone have an idea why this is happening?
function placeImages(arr){
let place = 0;
let num = 0;
let box = 1;
for(let i = 0; i < 10; i++){
num = arr[place];
const pic = document.createElement('img');
pic.id = `${num}`; //THIS IS THE PROBLEM
// pic.setAttribute('id', `${num}`); //number pics
pic.classList.toggle('pic');
pic.setAttribute('src', `./images/${num}.png`);
document.getElementById(`${box}`).appendChild(pic); //goes box by box and add image
box++;
place++;
}
console.log(arr);
}
The array is a random array of 10 numbers 1-5 only repeating once like {1, 3 , 2, 5, 5, 3, 2, 1, 4, 4}
The first image is with "pic.id = ${num};" commented out and the second one it is not commented out. I just started learning so sorry if the code is hard to understand.
result without id
result with id
So what I think this comes down to is that the ID attribute should be completely unique to each HTML element on a page. However, your code has multiple IDs that are the same. In the image you posted that was not displaying images it was where it was trying to give you one element with the ID of ${box} on line12. You expect this to be your div to place an image but instead, it probably got an image element that you created in a previous iteration of the loop. That is my guess and I hope that helps.
Take away: Keep IDs unique to every HTML Element!
What I recommend doing is something like this:
pic.id = `pic-${num}-${i}`;
Which will do something like this:
<img src="4.png" id="pic-4-2">
This way every ID will be unique because images will be prefixed with "pic" and postfixed with the iteration number. Then later in your code, you can splice out the middle number to match them to another image.
im using this script to rotate and change image when the page is refresh it working ok but sometimes it keep loading the same image several times before change to the new image, is there a way to fix this?
var theImages = [
"1.jpg",
"2.jpg",
"3.jpg"
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("headerbanner").src = theImages[x];
}
onload=changeImage
To achieve the image rotation behaviour that you require, you'll need to "remember" some state (ie the image that your were previously up to) between page loads. One easy way to do this is vial the LocalStorage API.
You can for instance, retrieve a previously stored value for a key via:
let lastIndex = localStorage.getItem('last_index');
And then use that to control which image is displayed from your array. You would also use:
localStorage.setItem('last_index', `${ lastIndex }`)
To update the stored value, for the next page reload. Together, these might integrate with your code like this:
/* Get the last stored index, and parse to an integer */
let lastIndex = Number.parseInt(localStorage.getItem('last_index'))
if(Number.isNaN(lastIndex)) {
/* If we got an invalid index (ie no previously stored value) set to default 0 */
lastIndex = 0;
}
else {
/* Otherwise increment the index counter. This is going to cause the image to
change every page load */
lastIndex ++;
}
/* Remember the updated index for future reloads */
localStorage.setItem('last_index', `${ lastIndex }`)
var theImages = [
"1.jpg",
"2.jpg",
"3.jpg"
];
function changeImage(){
var size=theImages.length;
/* Use the modulo operators to get x based on lastIndex, and the total number
of images */
var x = lastIndex % size;
document.getElementById("headerbanner").src = theImages[x];
}
window.onload=changeImage
Remember to keep in mind that the LocalStorage API sets values as strings, which is why Number.parseInt(),etc is necessary.
A good way to achieve the rotation after refresh would be to save your previous image index in the url and change it each time.
1) you land on the page, the query parameter image is empty, you get image with index 1 and you set your url to mysite.com?imageid=1
2) you refresh, the query parameter is 1, you set it to 2 in the url and display the image (there is no randomness here but you never get the same image)
3) implement custom logic to fit any index, you can implement randomness !== to previous image id to always get a different image with a recursive while loop:
while (newImageId === queryParam.imageId) { getRandomImageId(queryParam.imageId)}
I am on my phone can't write the code but you can use window.location for the url
Save the current image into the local session.
localStorage.setItem('lastImage', imageIndex);
After page load...
localStorage.getItem('lastImage');
... and exclude it from your random mechanism or ever iterate.
I am trying to use Javascript to select two random images from a local folder and place on separate Photoshop layers. I have created an array with the filepaths to choose from.
#target photoshop
var allImages = [“file path/img-1.jpg”, "file path/img-2.jpg", "file path/img-3.jpg"];
//this is a large array of file paths to 100 different images
var pickImage = allImages[Math.floor(Math.random() *
allImages.length)];
var imgFile = File(pickImage);
var openFile = app.open(imgFile);
var secondImage = allImages[Math.floor(Math.random() * allImages.length)];
app.activeDocument.artLayers.add(secondImage);
This opens the first image and creates a blank layer above but does not insert the second image. What am I missing?
In javascript, you must first create a file object before you may open an image. All you have to do is create the variable and then point it at secondImage. Just like you did with the first image:
var imgFile = File(pickImage);
In your current approach, your easiest solution would probably be to just make a variable secondPickedImage and assign it to the same thing as pickImage. Although, this leaves the possibility of you picking the same image, you could fix that with an if statement.
I would recommend changing your approach and turning pickImage into a function that you can call that will return a random number for your array - saves space, and cleans up your code. Then put the secondImage assignment in a do while loop that keeps picking a random number until you pick a number different from the pickImage number so your first and second pictures are different.
Source: http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-scripting-guide.pdf page 29.
How do i link all this images to an array, so as this links can work when i click each image slide
jQuery(document).ready(function() {
var bgImageArray = ["banner1.jpg", "banner2.jpg", "banner3.jpg"],
var links = ['http://google.com', 'http://hotmail.com', 'http://yahoo.com', 'http://kimjoyfox.com'],
base = window.location.origin + "/wp-content/themes/fbnquest/img/home/",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
The way I understand your problem is the following :
For each time you click on one of each of the images, you want to redirect the user to one of the URLs, changing the URL each time the user click on the image.
Is it what you want ? If not, please can you precise your problem
[EDIT]
So yes,
Here is my way of solving your problem, If you don't matter, I won't give you code, obviously, you do this for training, let's do it :
Create an eventListener on click that will trigger a function called ChangeImageUrl (for example) and assign that eventListener to all the img elements
Then create a function that will detect the current URL of the image clicked, using imgElement.src ( i advice you to devide the src string using split or equivalent, that way you can directly access by index the current url )
Once you have the URL Use yourUrlArray.indexOf(currentImageSrcUrl), to catch the index of the current URL in your array, store it and increment it ( bonus if the increment value is upper than the URL array length, set it to 0 )
access the new src using yourUrlArray[newindex]
assign current img element the new src that we juste have extracted
Tell me if this answer is good for you, I hope it will
I was trying to understand what do you really want and I did something that I hope help you.
Inside of the loop you can do in this way below.
var i = new Image();
i.src = base + img;
I've tried searching for several hours but cannot find an answer that works. I want to load a different image for each day of the year.
I have some js that creates a variable based on the date function. I concatenate this with other text strings to get this variable:
photo2load = http://www.example.com/photos/pic132.jpg
How do I then get this photo to load. What is the scripting required? I'm at a total loss.
Thanks in advance.
You need to add an id attribute to your image and then onload call a function with inside something like this:
function loadMyImage(){
var img = document.getElementById("id-of-image");
img.src = photo2Load;
}
Or if you want to pass directly your variable call the function like this
loadMyImage( photo2Load);
function loadMyImage(imgUrl){
var img = document.getElementById("id-of-image");
img.src = imgUrl ;
}