Arrays error - how to store a div element

Asked

Viewed 35 times

0

inserir a descrição da imagem aqui

The goal is to exchange the letter r for and to form the pre HTML element. I’ve had experiments with my code where I have an array of Divs where each div stores a letter. To swap the elements just exchange the order property, at least that was the logic I used. However, I can’t access the Divs attributes. When I access an array element from the index it gives me Undefined when I use a variable as an index, but when I use a number it doesn’t give me Undefined, but I can’t use a number. Why give me Undefined?

document.addEventListener('DOMContentLoaded', () => {

  var html5 = ['article', 'div', 'span', 'form', 'section', 'strong', 'pre', 'table', 'main', 'blockquote'];
  var playButton = document.getElementById("play");
  var instructionsButton = document.getElementById("instructions");
  var creditsButton = document.getElementById("credits");
  var introductionBox = document.getElementById("introduction");
  var menuBox = document.getElementById("menu");
  var gameBox = document.getElementById("gameBox");
  var html5Button = document.getElementById("html5Button");
  var css3Button = document.getElementById("css3Button");
  var javascriptButton = document.getElementById("javascriptButton");
  var sqlButton = document.getElementById("sqlButton");


  instructionsButton.addEventListener("click", () => {
    alert("Instructions");
  });

  creditsButton.addEventListener("click", () => {
    alert("Credits");
  });

  playButton.addEventListener("click", () => {
    introductionBox.classList.add("hidden");
    menuBox.classList.remove("hidden");
    playButton.disabled = "true";
    html5Button.addEventListener("click", () => {
      menuBox.classList.add("hidden");
      var game = new Game();
      game.displayBox();
      // Append a child h3 element refering to the technology
      var nameTechnology = document.createElement("h3");
      nameTechnology.innerHTML = "HTML5";
      gameBox.appendChild(nameTechnology);

      game.gameInteraction();
    })
  });

  var Game = class Game{
    displayBox(){
      gameBox.classList.remove("hidden");
    }
    choseWord(){ // Returns one random word
      var len = html5.length;
      var wordIndex = Math.floor(Math.random() * len);
      return html5[wordIndex];
    }
    gameMechanics(){
      var word = this.choseWord(); // Gets the word chosen
      var lenWord = word.length; // Gets the length of the word chosen
      var wordBox = document.createElement("div"); // Creates a div that contain the word
      wordBox.classList.add("wordBox");
      for(var i = 0; i < lenWord; i++){
        var letter = document.createElement("div"); // Creates a div that contains the letters
        letter.innerHTML = word[i]; // Appends the letter to the div
        wordBox.appendChild(letter); // Appends the div to its parent
      }
      gameBox.appendChild(wordBox); // Appends the div to the gameBox
      var lettersArray = document.querySelector(".wordBox").querySelectorAll("div"); // Gets an array of letters
      lettersArray.forEach((div) => {
        div.style.order = Math.floor(Math.random() * lenWord); // Switches the order of the letters
      });
      return [lettersArray, word];
    }
    gameInteraction(){
      var turn = 0;
      var gameMechanics = this.gameMechanics();
      var letters = gameMechanics[0];
      var word = gameMechanics[1];
      letters.forEach((letter) => {
        letter.addEventListener("click", (e) => {
          if(turn % 2 === 0){
            var indexLetterToSwitch = letter.style.order;
            var lettertoSwitch = word.indexOf(letter.innerHTML);
            console.log(lettertoSwitch);
            turn ++;
          }else if(turn % 2 === 1){
            var indexLetterToBeSwitchedWith = letter.style.order;
            console.log(indexLetterToBeSwitchedWith);
            turn ++;
            
          }
          if(turn % 2 == 0 && turn !== 0){
            letter.style.order = indexLetterToSwitch;
            console.log(letters[0]); // Retorna-me a div
            letters[lettertoSwitch].attributes[0].value = "order: " + String(indexLetterToBeSwitchedWith + "; "); // Dá erro diz que não consegue aceder aos atributos de undefined
          }
        })
      })
    }
  }

});
* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}

nav {
  width: 100%;
  height: 60px;
  background-color: rgba(0, 255, 255, 0.7);
  border-radius: 50px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-pack: distribute;
      justify-content: space-around;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

nav button {
  width: 30vw;
  height: 30px;
  border-radius: 10px;
  font-size: 1.1rem;
  font-weight: bolder;
  background-color: rgba(0, 255, 255, 0.7);
  color: red;
  -webkit-box-shadow: 0px 10px 20px rgba(255, 0, 0, 0.8);
          box-shadow: 0px 10px 20px rgba(255, 0, 0, 0.8);
}

.box {
  width: 90%;
  border: 2px solid red;
  border-radius: 20px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -ms-flex-wrap: wrap;
      flex-wrap: wrap;
  padding: 15px;
  margin: auto;
  margin-top: 20px;
}

.box h2 {
  width: 100%;
  text-align: center;
  margin-bottom: 20px;
  font-size: 1.7rem;
  color: red;
}

#menuContainer {
  height: 600px;
  max-height: 40vh;
  overflow: scroll;
}

#menuContainer::-webkit-scrollbar-track {
  opacity: 0;
}

#menuContainer::-webkit-scrollbar-thumb {
  background-color: red;
  border-radius: 20px;
}

#menuContainer::-webkit-scrollbar {
  width: 12px;
}

.box #menuContainer button {
  width: 100%;
  margin-bottom: 10px;
  height: 7vh;
  border-radius: 10px;
  border: none;
  background-color: aqua;
  color: red;
  font-size: 1.2rem;
  -webkit-transition: all 0.3s ease-out;
  transition: all 0.3s ease-out;
}

.box #menuContainer button:hover {
  cursor: pointer;
  background-color: red;
  font-weight: bolder;
  color: aqua;
}

.wordBox {
  width: 100%;
  margin-top: 20px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.wordBox div {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  border: 1px solid aqua;
  text-align: center;
  vertical-align: middle;
  font-size: 1.3rem;
}

.wordBox div:not(:last-child) {
  margin-right: 5px;
}

.hidden {
  display: none;
}
/*# sourceMappingURL=styles.css.map */
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>TechQuiz Game</title>
  <link rel="stylesheet" href="./css/styles.css">
  <script src="./js/app.js" defer></script>
  <script src="./js/data.js" defer></script>
</head>
<body>
  
  <header>
    <nav>
      <button id="play">Play</button>
      <button id="instructions">Instructions</button>
      <button id="credits">Credits</button>
    </nav>
  </header>

  <main>

    <div class="box" id="introduction">
      <h2>Introduction</h2>
      <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Necessitatibus, iusto. Laudantium sint recusandae ullam soluta, ipsum tempore a quae repellendus.</p>
    </div>

    <div class="box hidden" id="menu">

      <h2>Menu</h2>

      <div id="menuContainer">
        <button id="html5Button">HTML5</button>
        <button id="css3Button">CSS3</button>
        <button id="javascriptButton">JAVASCRIPT</button>
        <button id="sqlButton">SQL</button>
      </div>

    </div>

    <div class="box hidden" id="gameBox">

    </div>

  </main>

</body>
</html>

How to change the letters? Why give me Undefined? What is a solution to this problem?

  • 1

    The lettertoSwitch variable is inside an if block so it is not defined.

  • Problem solved! Ty

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.