Skip to content
Advertisement

Using a for loop to display HTML element using JavaScript

I’m currently working on a project where I have a gallery (Gallery.php) containing a carousel of images, if an image is clicked on, the ImageID (I have set) and the Image URL are added to a 2D array in the localStorage. I am attempting to retrieve the array from localStorage in the homepage (index.php) which works as confirmed by logging to the console, however I am struggling to find a way to loop through the array and display a bootstrap card where the header is the ImageID and the body is an image with the URL. I realise this would be easier in PHP, but the project briefing asks for this to be done explicitly in JavaScript. Here is the psuedocode for what I am trying to achieve

FOR image IN ImageArray
   CREATE card
   SET card.header TO image.ImageID
   SET card.body TO img element SRC = ImageURL
   END CARD
ENDFOR

This is the function which sets the ImageID and URL, and then pushes to the localStorage array

function SetClickedPhotoURL(URL, ImageID) {
    //Check if item is already set
    for (let x = 0; x<images.length; x++) {
        if (images[x][0] == ImageID) {
            console.log("Image already added");
            //Cancel function
            return;
        }
    }
    images.push([ImageID, URL]);
    window.localStorage.setItem("images", JSON.stringify(images));
}

I am trying to achieve a similar effect of using a foreach loop in PHP, I am also using JQuery in this project if a solution is available through it.

The PHP for this solution would be something along the lines of this if it helps you understand what I am trying to achieve.

<?php
foreach ($ImageArray as $Image) {
   ?>
   <div class="col-md-4 col-12 mb-3">
       <div class="card border">
           <div class="card-header text-center">
               <h5><?php echo $Image[0];?></h5> <!--$Image[0] is the ImageID-->
           </div>
           <div class="card-body text-center">
              <img src=<?php echo $Image[1];?> class="img-fluid" alt=<?php echo $ImageID;?>/>
              <!--$Image[1] is where the URL is stored-->
           </div>
       </div>
    </div>
    <?php
}
?>

Any help would be greatly appreciated!

Advertisement

Answer

Loop through the images, and for each element, create a card and append it to the destination (assume to be #target):

images.forEach(function(image) {
   $('#target').append(
   `<div class="col-md-4 col-12 mb-3">
       <div class="card border">
           <div class="card-header text-center">
               <h5>${image[0]}</h5>
           </div>
           <div class="card-body text-center">
              <img src="${image[1]}" class="img-fluid" alt="${image[0]}"/>
           </div>
       </div>
    </div>
    `
    );
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement