Home > Software engineering >  Javascript Won't replace image
Javascript Won't replace image

Time:10-08

My Js code below is a quiz game. Each question takes up a full page, which means we have to change all the content every time the user presses the next button.

My issue is, i can't seem to get the image to switch to the next by fully replacing it. In my case the new images just go to the bottom of the first.

// Questions will be asked//
const Questions = [
 { id: 0, i: "images/trump.jpg", a: [{ text: "George Washington", isCorrect: false },  { text: "John Adams", isCorrect: false }, { text: "James Madison", isCorrect: false },  { text: "Donald John Trump", isCorrect: true } ] }, 
 { id: 1, i: "http://www.google.com/intl/en_com/images/logo_plain.png", a: [{ text: "Lampang", isCorrect: false, isSelected: false }, { text: "phuket", isCorrect: false }, { text: "Ayutthaya", isCorrect: false }, { text: "Bangkok", isCorrect: true } ] }, 
 { id: 2, i: "http://www.google.com/intl/en_com/images/logo_plain.png", a: [{ text: "surat", isCorrect: false }, { text: "vadodara", isCorrect: false }, { text: "gandhinagar", isCorrect: true }, { text: "rajkot", isCorrect: false } ] } 
]

// Set start//
var start = true;

// Iterate//
function iterate(id) {

  // Getting the result display section//
  var result = document.getElementsByClassName("result");
  result[0].innerText = "";

  //Adding an image//

  var img = document.createElement("img");
  img.src = Questions[id].i;
  var src = document.getElementById("image");
  src.appendChild(img);


  // Getting the options//
  const op1 = document.getElementById('op1');
  const op2 = document.getElementById('op2');
  const op3 = document.getElementById('op3');
  const op4 = document.getElementById('op4');


  // Providing option text//
  op1.innerText = Questions[id].a[0].text;
  op2.innerText = Questions[id].a[1].text;
  op3.innerText = Questions[id].a[2].text;
  op4.innerText = Questions[id].a[3].text;

  // Providing the true or false value to the options//
  op1.value = Questions[id].a[0].isCorrect;
  op2.value = Questions[id].a[1].isCorrect;
  op3.value = Questions[id].a[2].isCorrect;
  op4.value = Questions[id].a[3].isCorrect;

  var selected = "";

  // Show selection for op1//
  op1.addEventListener("click", () => {
    op1.style.backgroundColor = "lightgoldenrodyellow";
    op2.style.backgroundColor = "lightskyblue";
    op3.style.backgroundColor = "lightskyblue";
    op4.style.backgroundColor = "lightskyblue";
    selected = op1.value;
  })

  // Show selection for op2//
  op2.addEventListener("click", () => {
    op1.style.backgroundColor = "lightskyblue";
    op2.style.backgroundColor = "lightgoldenrodyellow";
    op3.style.backgroundColor = "lightskyblue";
    op4.style.backgroundColor = "lightskyblue";
    selected = op2.value;
  })

  // Show selection for op3//
  op3.addEventListener("click", () => {
    op1.style.backgroundColor = "lightskyblue";
    op2.style.backgroundColor = "lightskyblue";
    op3.style.backgroundColor = "lightgoldenrodyellow";
    op4.style.backgroundColor = "lightskyblue";
    selected = op3.value;
  })

  // Show selection for op4//
  op4.addEventListener("click", () => {
    op1.style.backgroundColor = "lightskyblue";
    op2.style.backgroundColor = "lightskyblue";
    op3.style.backgroundColor = "lightskyblue";
    op4.style.backgroundColor = "lightgoldenrodyellow";
    selected = op4.value;
  })

  // Grabbing the evaluate button//
  const evaluate = document.getElementsByClassName("evaluate");

  // Evaluate method//
  evaluate[0].addEventListener("click", () => {
    if (selected == "true") {
      result[0].innerHTML = "True";
      result[0].style.color = "green";
    } else {
      result[0].innerHTML = "False";
      result[0].style.color = "red";
    }
  })
}

if (start) {
  iterate("0");
}

// Next button and method//
const next = document.getElementsByClassName('next')[0];
var id = 0;


next.addEventListener("click", () => {

  setTimeout(() => {
    start = false;
    if (id < 2) {
      id  ;
      iterate(id);
      console.log(id);

    }
  })


})
:root {
  --primary: #1D1D1F;
  --secondary: #858786;
  --erro: #FF5757;
  text-align: center;
  align-items: center;
  align-self: center;
  font-family: SF Pro Display, SF Pro Icons, AOS Icons, Helvetica Neue, Helvetica, Arial, sans-serif;
}

.column {
  justify-items: center;
  justify-content: center;
  float: left;
  width: 50%;
  justify-content: center;
}

.main-container {
  margin: 50px;
  border-radius: 20px;
  background-color: #F5F8FA;
}


/* Clear floats after the columns */

.main-container:after {
  content: "";
  display: table;
  clear: both;
}

.main-container img {
  width: 320px;
  height: 320px;
  border-radius: 20px;
  object-position: center;
  object-fit: cover;
}

.center-cropped img {
  border-radius: 2px;
  width: 50%;
  height: 50%;
  object-position: center;
  object-fit: cover;
}

.option-container {
  margin-top: 50%;
  margin-bottom: 50%;
  grid-column: 1;
  margin: 10px;
  padding: 5px;
  width: 100%;
  height: auto;
}

.quiz-image {
  margin: 10px;
  padding: 10px;
  width: 100%;
}

.bottom-left {
  position: absolute;
  bottom: 8px;
  left: 16px;
}

.option {
  border-radius: 10px;
  border-width: 0px;
  margin: 10px;
  padding: 10px;
  width: 50%;
  height: auto;
  font-size: 1rem;
  font-weight: 600;
  color: white;
  background-color: #1da1f2;
}

.option:hover {
  background-color: #e1e8ed;
}

.title h1 {
  font-size: 4rem;
  font-weight: 400;
  padding: 10px;
  color: #1d1d1d;
}

.title h2 {
  font-size: 1.5rem;
  font-weight: 400;
  color: #1D1D1D;
}

h2 {
  font-size: 3rem;
  font-weight: 300;
  color: #1D1D1D;
}

.question-container {
  margin: 10px;
  padding: 5px;
  width: 80vw;
  height: 10vh;
  background-color: #c7dddf;
  font-size: x-large;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div >
  <h1>Guess The President</h1>
</div>
<div  &nbsp;>
  <div ></div>
  <div >
    <div  id="image"></div>
  </div>
  <div >
    <div >
      <button  onclick="" id="op1">option1</button>
      <button  id="op2">option2</button>
      <button  id="op3">option3</button>
      <button  id="op4">option4</button>
    </div>
  </div>
</div>
<div >
  <button >Evaluate</button>
  <button >Next</button>
</div>

CodePudding user response:

Where you have your

src.appendChild(img);

Change it to this:

src.innerHTML = "";
src.appendChild(img);

This will clear out the previous image and the new one will be added in.

Hope this helps.

CodePudding user response:

Just for the heck of it. Not really an answer, but thought your question used jQuery but your code did not use it (sorry, Andy, it's a mess!). The following code is dynamic and will adapt to how many questions you have, each may contain a varying amount of different answers.

// Questions will be asked//
const questions = [
  { id: 0, i: "https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Donald_Trump_official_portrait.jpg/330px-Donald_Trump_official_portrait.jpg", a: [{ text: "George Washington", isCorrect: false },  { text: "John Adams", isCorrect: false }, { text: "James Madison", isCorrect: false },  { text: "Donald John Trump", isCorrect: true } ] }, 
  { id: 1, i: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Bangkok_Montage_2021.jpg/375px-Bangkok_Montage_2021.jpg", a: [{ text: "Lampang", isCorrect: false, isSelected: false }, { text: "phuket", isCorrect: false }, { text: "Ayutthaya", isCorrect: false }, { text: "Bangkok", isCorrect: true } ] }, 
  { id: 2, i: "https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Akshardham_Gandhinagar_Gujarat.jpg/405px-Akshardham_Gandhinagar_Gujarat.jpg", a: [{ text: "surat", isCorrect: false }, { text: "vadodara", isCorrect: false }, { text: "gandhinagar", isCorrect: true }, { text: "rajkot", isCorrect: false } ] } 
];

// Set start//
const game = {
  active: true,
  currentQuestion: 0,
  selectedAnswer: null,
  evaluated: false,
  score: 0
};


function updateAnswerStatus() {
  const progressText = `${game.currentQuestion   1} / ${questions.length} - ${game.score} pts`;
  const hasNext = game.currentQuestion < questions.length - 1;

  $('#result').text(progressText);
  
  $('#btnEvaluate').attr('disabled', game.evaluated || !game.selectedAnswer);
  $('#btnNext').attr('disabled', !game.evaluated || !hasNext);
}

function selectAnswer(selectedAnswer) {
  if (!game.evaluated) {
    game.selectedAnswer = selectedAnswer;
  
    $('#optionList .option').each(function () {
      const option = $(this);
      const answer = option.data('answer');
    
      if (answer === selectedAnswer) {
        option.addClass('selected');
      } else {
        option.removeClass('selected');
      }
    });

    updateAnswerStatus()
  }
}

function evaluateAnswer() {
  if (!game.evaluated && game.selectedAnswer) {
    game.evaluated = true;
    
    $('#optionList .option').each(function () {
      const option = $(this);
      const answer = option.data('answer');

      if (answer === game.selectedAnswer) {
        option.addClass( answer.isCorrect ? 'correct' :  'incorrect');
      
        game.score = game.score   (answer.isCorrect ? 1 : 0);
      }
    });
    
    updateAnswerStatus();
  }
}

function createOption(answer) {
  return $('<button>')
    .data({ answer })
    .text(answer.text)
    .addClass('option')
    .on('click', function() {
      selectAnswer(answer);
    })
  ;
}

function renderCurrentQuestion() {
  const question = questions[game.currentQuestion];
    
  if (question) {
    const optList = $('#optionList').empty();
    const image = $('#image').empty();

    game.selectedAnswer = null;
    game.evaluated = false;

    image.append($('<img>').attr('src', question.i));
    
    for (const answer of question.a) {
      optList.append( createOption(answer) );
    }
  }  
       
  updateAnswerStatus();
};

// next question?
$('#btnNext').on('click', function() {
  game.currentQuestion = game.currentQuestion   1;
  renderCurrentQuestion();
}).attr('disabled', true);

$('#btnEvaluate').on('click', function() {
  evaluateAnswer();
});

if (game.active) {
  renderCurrentQuestion();
}
:root {
  --primary: #1D1D1F;
  --secondary: #858786;
  --erro: #FF5757;
  text-align: center;
  align-items: center;
  align-self: center;
  font-family: SF Pro Display, SF Pro Icons, AOS Icons, Helvetica Neue, Helvetica, Arial, sans-serif;
}

.column {
  justify-items: center;
  justify-content: center;
  float: left;
  width: 50%;
  justify-content: center;
}

.main-container {
  margin: 50px;
  border-radius: 20px;
  background-color: #F5F8FA;
}


/* Clear floats after the columns */

.main-container:after {
  content: "";
  display: table;
  clear: both;
}

.main-container img {
  width: 320px;
  height: 320px;
  border-radius: 20px;
  object-position: center;
  object-fit: cover;
}

.center-cropped img {
  border-radius: 2px;
  width: 50%;
  height: 50%;
  object-position: center;
  object-fit: cover;
}

.option-container {
  margin-top: 50%;
  margin-bottom: 50%;
  grid-column: 1;
  margin: 10px;
  padding: 5px;
  width: 100%;
  height: auto;
}

.quiz-image {
  margin: 10px;
  padding: 10px;
  width: 100%;
}

.bottom-left {
  position: absolute;
  bottom: 8px;
  left: 16px;
}

.option {
  border-radius: 10px;
  border-width: 0px;
  margin: 10px;
  padding: 10px;
  width: 50%;
  height: auto;
  font-size: 1rem;
  font-weight: 600;
  color: white;
  background-color: #1da1f2;
}

.option:hover {
  color: #1da1f2;
  background-color: #d1d8dd;
}
.option.selected {
  background-color: #bbbb33;
}
.option.selected:hover {
  color: white;
  background-color: #777733;
}
.option.selected.incorrect {
  background-color: #bb3333;
}
.option.selected.correct {
  background-color: #33bb33;
}

.title h1 {
  font-size: 4rem;
  font-weight: 400;
  padding: 10px;
  color: #1d1d1d;
}

.title h2 {
  font-size: 1.5rem;
  font-weight: 400;
  color: #1D1D1D;
}

h2 {
  font-size: 3rem;
  font-weight: 300;
  color: #1D1D1D;
}

.question-container {
  margin: 10px;
  padding: 5px;
  width: 80vw;
  height: 10vh;
  background-color: #c7dddf;
  font-size: x-large;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div >
  <h1>Guess the answer</h1>
</div>
<div  &nbsp;>
  <div id="result" ></div>
  <div >
    <div id="image"></div>
  </div>
  <div >
    <div id="optionList" ></div>
  </div>
</div>
<div >
  <button id="btnEvaluate" >Evaluate</button>
  <button id="btnNext" >Next</button>
</div>

  • Related