Search code examples
javascriptarraysimagelightbox2

How to Display an Image Array with JS and Use Lightbox2


How do you display all the images from an array in JS and still use Lightbox2?

8th gr math teacher trying to create a Tic Tac Toe board of images where Lightbox2 allows users to click to enlarge images. In the code, you will see I randomize the array to make it harder for my kids to cheat. The focus though is to get the array to display each img into a 3x3 grid, but allow students to click and enlarge each image with a modal.

Lightbox2 requires the following line of code:
a href="images/image-1.jpg" data-lightbox="image-1" data-title="My caption">Image #1 /a This is why I have all the inefficient + signs in the js document.write code.

I have searched for the answer here where answers edit the DOM or increment through the array using .foreach, I have yet to see a solution where you can still click to enlarge the image in a modal. Thank you and my students will say thank you! This is my first venture into bringing computer science to the classroom, so I am very much a noob.

<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<link href="https://fonts.googleapis.com/css?
family=Oswald:300,700|Varela+Round" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="tictactoestyle.css">
<link href="css/lightbox.css" rel="stylesheet">
<script type="text/javascript" src="tictactoe.js"></script>
<script src="js/lightbox-plus-jquery.js"></script>
</head> 

<body>
<div class="title">
<h1>  Tic Tac Toe </h1>
</div>

<div id="gameboard">  <!--Container for all nine divs-->

<script>displayAllImages();</script>
</div>
</body>
</html>

/*Javascript*/

function shuffle(arr) {
var currentIndex = arr.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = arr[currentIndex];
    arr[currentIndex] = arr[randomIndex];
    arr[randomIndex] = temporaryValue;
}

return arr;

function displayAllImages() {
var imgArray = [];
imgArray[0] = "image1";
imgArray[1] = "image2";
imgArray[2] = "image3";
imgArray[3] = "image4";
imgArray[4] = "image5";
imgArray[5] = "image6";
imgArray[6] = "image7";
imgArray[7] = "image8";
imgArray[8] = "image9";

imgArray = shuffle(imgArray);

for (i=0;i<imgArray.length;i++) {
    document.write("<div class='card'><a href='images/" + item + "'.jpg 
data-lightbox='" + item + "'><img src='images/" + item + "m.jpg'></a>
</div>");

Solution

  • A few things you'll need to do. First you can't just add a div as a string and write it to the DOM. jQuery let's you do something like that, but vanilla JS won't recognize it as an actual element. There were also a few missing brackets in there. I've added comments inline to help make things clear. Give this a try:

    function shuffle(arr) {
      var currentIndex = arr.length, temporaryValue, randomIndex;
    
          // While there remain elements to shuffle...
      while (0 !== currentIndex) {
    
          // Pick a remaining element...
          randomIndex = Math.floor(Math.random() * currentIndex);
          currentIndex -= 1;
    
          // And swap it with the current element.
          temporaryValue = arr[currentIndex];
          arr[currentIndex] = arr[randomIndex];
          arr[randomIndex] = temporaryValue;
      }
    
      return arr;
    }
    
    
    function displayAllImages() {
      var imgArray = [
        "image1",
        "image2",
        "image3",
        "image4",
        "image5",
        "image6",
        "image7",
        "image8",
        "image9",
      ];
    
      //Map over the array to create the DOM elements
      var domElements = imgArray.map(function(imgName, index) {
        var cardDiv = document.createElement('div');
        var cardLink = document.createElement('a');
        var cardImage = document.createElement('img');
    
        //Add the class
        cardDiv.classList.add('card');
    
        //Add the link to image
        //Utilize interpolation for the variable
        //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
        cardLink.href = `images/${imgName}.jpg`;
    
        //Set the data attribute
        cardLink.dataset.lightbox = imgName;
    
        //Set img source
        cardImage.src = `images/${imgName}.jpg`;
    
        //Put it all together
        cardLink.appendChild(cardImage);
        cardDiv.appendChild(cardLink);
    
        return cardDiv;
    
      });
    
      //Now we have an array with the propper DOM elements
      //Shuffle it
      var shuffled = shuffle(domElements);
    
      //Append the elements to the DOM
      var body = document.querySelector('body');
    
      shuffled.forEach(function(card, index) {
        body.appendChild(card);
      });
    }
    

    Hope that helps point you in the right direction. Happy coding!