Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
addEventListener in a loop

I'm new in this nice community. I am a young student in computer science and I'm trying to develope a web based app to help both sighted people and people with visual empairment to learn typing. My project was blocked by the following problem: Given a string, I need to verify that the user has pressed the key that corresponds to the first character. If it is correct, the program should test the next character, until the end of the string. The most natural solutions seems to be a loop, like that:

        do {
        var checkCharacter=lessons[exerciceNumber][2].substr(charNumber, 1);
        document.addEventListener('keydown', testKey);
    }
    while (charNumber<=lessons[exerciceNumber][2].length-1);

When I run the script, nothing appears and it seems it doesn't detect the pressed keys. Can you help me please? Inorder to understand the context, I'll attach the entire file.

<?php
include "config.php";
//Select fields from database
$sql="SELECT lesson_number, exercice_number, text FROM lessons";
$result=$conn->query($sql);
//Pass variables to javascript
$output="<script> var lessons=new Array(); ";
while ($row=$result->fetch_assoc()) {
    $output.="lessons.push([
        ".$row["lesson_number"].",
        ".$row["exercice_number"].",
        '".$row["text"]."']);";
}
$output.="</script>";
echo $output;
?>
<html>
<head>
    <title>Impara a scrivere</title>
</head>
<body>
    <h2 id="lesson"></h2>
    <p id="instructions"></p>
    <p id="check"></p>
    <p id="keyList"></p>
</body>
<script>
    //define variables
    var keys="";
    var exerciceNumber=0;
    var charNumber=0;
    //Function to play the sounds
    function sound(name) {
        var audio=new Audio(name+'.mp3');
        audio.play();}
    document.getElementById("lesson").innerHTML="Lezione "+lessons[exerciceNumber][0];
    document.getElementById("instructions").innerHTML="Esercizio "+lezioni[exerciceNumber][1]+": scrivi <b>"+lessons[exrciceNumber][2]+"</b>.";
    //function to check pressed keys
    funtion testKey(event) {
        if (event.key==checkCharacter) {
            sound ("right");
            keys+=event.key;
            document.getElementById("keyList").innerHTML=keys;
        } else {
            sound("wrong");
        }
    }
    //loop for the exercices
    do {
        var checkCharacter=lessons[exerciceNumber][2].substr(charNumber, 1);
        document.addEventListener('keydown', testKey);
    }
    while (charNumber<=lessons[exerciceNumber][2].length-1);
</script>
</html>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You cannot add an event listener multiple times, that will cause it to fire once. To avoid this, try using onkeydown. For example, something like this should work:

    do {
        const checkCharacter = lessons[exerciceNumber][2].substr(charNumber, 1);
        document.onkeydown = (evt) => {
            testKey();
        };
    } while (charNumber <= lessons[exerciceNumber][2].length - 1);

Also, I'm not entirely sure of what you're trying to do here, but instead of using a loop you can do something like this:

form.onsubmit = (evt) => {
     const input = someInput.value;
     if (testKey() === input) {
        return true; // Or whatever you want
     }
};

Hoped this helped!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda