Home  >  Q&A  >  body text

Assign forEach to each image via 'img'

<p>I'm trying to use forEach in JS under the img tag in HTML. </p><p>This is the variable bobbingPhotos: </p> <pre class="brush:php;toolbar:false;">bobbingPhotos.forEach(function(photo) { var randomDelay = Math.random() * 2; // Random delay between 0 and 2 seconds photo.style.animationDelay = randomDelay 's'; });</pre> <p>This problem could be solved by assigning each image a hardcoded class name "bobbing-photo", but I cannot do this because my images are generated from text input. </p> <pre class="brush:php;toolbar:false;">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"); }</pre> <p>Even using image.classList.add("bobbing-photo"), there is no way to make each image float up and down at different points in time. </p><p>Is there any way to solve this problem? </p><p><br /></p>
P粉998100648P粉998100648449 days ago422

reply all(1)I'll reply

  • P粉512526720

    P粉5125267202023-07-29 12:11:27

    Since you added the image tag dynamically, the animation function should be called again after adding the image tag.

    generateImages();
        // todo here get elements by classname
        var bobbingPhotos = ...
        // call animation function again
        bobbingPhotos.forEach(function(photo) {
          var randomDelay = Math.random() * 2; // Random delay between 0 and 2 seconds
          photo.style.animationDelay = randomDelay + 's';
        });

    reply
    0
  • Cancelreply