Home > Software design >  javascript I have a sequence that runs continuously, but need it to stop when an image is clicked
javascript I have a sequence that runs continuously, but need it to stop when an image is clicked

Time:11-11

I have very little to no knowledge when it comes to using JavaScript. I have 24 of the same image given an id from q1 - q24. my code allows for the 24 images to be changed to image2 one at a time, but I need for it to stop and display a text/alert when image2 is clicked.

<script>
{
    let num = 1;
    function sequence()
    {
        let back = 1;
        while (back < 25)
        {
            if(back == 1)
            {
                document.getElementById("q24").src = "question.jpg"; 
            }
            else
            {
                document.getElementById("q"   (back-1)).src = "question.jpg"; 
            }

            back  
        }

        document.getElementById("q"   num).src = "question2.png";
        num = num   1;
        if(num > 24){num = 1;}
    }


    setInterval(sequence, 500);
}


</script>

CodePudding user response:

Save the interval timer to a variable. Then add a click listener to all the images that stops the timer if the current image is the one showing question2.jpg.

{
  let num = 1;

  for (let i = 1; i <= 24; i  ) {
    document.getElementById(`q${i}`).addEventListener("click", function() {
      if (i == num) {
        clearInterval(interval);
      }
    });
  }

  let interval = setInterval(sequence, 500);

  function sequence() {
    for (let i = 1; i <= 24; i  ) {
      if (i == num) {
        document.getElementById(`q${i}`).src = "question2.jpg";
      } else {
        document.getElementById(`q${i}`).src = "question.jpg";
      }

      num = num   1;
      if (num > 24) {
        num = 1;
      }
    }
  }
}

CodePudding user response:

While I don't fully understand your use case, you could create a click event listener on the document and check the target's src in it.

document.addEventListener('click', function(e) {
  if (e.target.src === 'question2.png') {
    alert('Clicked question 2');
  }
});
  • Related