Ibrahim
Ibrahim

Reputation: 201

I'm trying to create a quiz with a picture for each question. Im using switch statement. Is a way to simplify the code as I have 20 questions?

const assignPictures = (value, questionID) => {
  const addPicture = document.createElement("div");
  addPicture.setAttribute("class","imagesInQuestion")

  switch(true){
    case value === secondArray[0]:
      addPicture.innerHTML = `<img class="inlineImages" src ="/Images/Block1.png">`
      break;

    case value === secondArray[1]:
      addPicture.innerHTML = `<img class="inlineImages" src ="/Images/Block2.png">`
      break;
   }
   return document.querySelector(questionID).append(addPicture);
}

Upvotes: 1

Views: 64

Answers (1)

Puka
Puka

Reputation: 1585

Based on OP's comment, you could use an array to associate each question with a path to a file. Then, you would use this array to display the good image based on the current question index:

const assignPictures = (value, questionID) => {
    // each item is the path to the relevant image
    const images = [
        '/Images/Block1.png',
        '/another_path.jpg',
        'https://external.image.jpg',
    ];

    // if `questionID` is not a numerical index, adjust `images` accordingly:
    // const images = {
    //     firstQuestion: '/Images/Block1.png',
    //     anotherID: '/another_path.jpg',
    //     whyNot: 'https://external.image.jpg',
    // }

    const addPicture = document.createElement("div");
    addPicture.setAttribute("class", "imagesInQuestion")
    // assuming `questionID` is the current question number
    addPicture.innerHTML = `<img class="inlineImages" src ="${images[questionID]}">`
    document.querySelector(questionID).append(addPicture);
}

Please, note that we are using backticks to create a template literal:

// This allows us to use this syntax:
`<img class="inlineImages" src ="${images[questionID]}">`

// rather than this one:
'<img class="inlineImages" src ="' + images[questionID] + '">';

Upvotes: 1

Related Questions