I am trying to use forEach
in JS under the img
tag on HTML
Here is the variable bobbingPhotos
:
bobbingPhotos.forEach(function(photo) {
var randomDelay = Math.random() * 2; // Random delay between 0 and 2 seconds
photo.style.animationDelay = randomDelay + 's';
});
This can be solved through giving each and every image a hard coded class="bobbing-photo"
but I cannot do that as my images are being generated through text inputs
function generateImages() {
var userInput = document.getElementById('userInput').value;
var imageOutput = document.getElementById('imageOutput');
imageOutput.innerHTML = '';
for (var i = 0; i < userInput.length; i++) {
var character = userInput[i].toUpperCase();
var element;
if (character === "n") {
element = document.createElement('br');
}
else if (character === ' ') {
element = document.createElement('img');
element.src = 'FONT/SPACE.png';
}
else {
var image = document.createElement('img');
image.src = 'FONT/' + character + '.png';
element = image;
image.classList.add("bobbing-photo");
}
Even doing image.classList.add("bobbing-photo")
does not make each and every image bob at a different time.
Is there a way to solve this?
2
Answers
Because you added the image tag dynamically, the animation function should be called again after add image tags.
Here is a simplified working example. If this works for you, maybe you can re-examine your own code and fix the issue?