Home > other >  Using a for loop to display HTML element using JavaScript
Using a for loop to display HTML element using JavaScript

Time:05-22

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 >
       <div >
           <div >
               <h5><?php echo $Image[0];?></h5> <!--$Image[0] is the ImageID-->
           </div>
           <div >
              <img src=<?php echo $Image[1];?>  alt=<?php echo $ImageID;?>/>
              <!--$Image[1] is where the URL is stored-->
           </div>
       </div>
    </div>
    <?php
}
?>

Any help would be greatly appreciated!

CodePudding user response:

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 >
       <div >
           <div >
               <h5>${image[0]}</h5>
           </div>
           <div >
              <img src="${image[1]}"  alt="${image[0]}"/>
           </div>
       </div>
    </div>
    `
    );
});
  • Related