Skip to content
Fix Code Error

Why doesnt my table sort my div variable in numerical order?

June 30, 2021 by Code Error
Posted By: Anonymous

When playing the game, my proposed code will

  1. Determine your final score after the end of the game i.e. the Gamer Over section
  2. This final score is transferred and visualised onto a table
  3. When pressing the ‘Sort’ button/text, the table will rearrange itself in numerical order

As of currently, <div id="total-score">0</div> is used to display the players final score, and is easily navagable via subpages at the top of the window. As long as the user does not reset their score, this final score remains visibe, however, when sorting the table, it still remains in its initial position, while the other cells will correctly re-arrange themselves.

Could any of you provide suggestions as to how to fix this issue?

_x000D_

_x000D_

<html>

<head>
  <style>
    table {
      border-collapse: collapse;
    }
    
    th,
    td {
      border: 1px solid #aaa;
      padding: 5px;
      text-align: left;
    }
    
    * {
      box-sizing: border-box
    }
    /* Set height of body and the document to 100% */
    
    body,
    html {
      height: 100%;
      margin: 0;
      font-family: adventure;
    }
    /* Style tab links */
    
    .tablink {
      background-color: #111;
      color: Yellow;
      float: left;
      border: none;
      outline: none;
      cursor: pointer;
      padding: 14px 16px;
      font-size: 17px;
      width: 25%;
    }
    
    .tablink:hover {
      background-color: #999;
    }
    /* Style the tab content (and add height:100% for full page content) */
    
    .tabcontent {
      color: black;
      display: none;
      padding: 100px 20px;
      height: 100%;
    }
    
    p5 {
      width: 20%;
      height: 10%;
      position: absolute;
      top: 800px;
      right: 300px;
      font-family: Arial;
      text-align: center;
      font-size: 30px;
      color: white;
      border: none;
      outline: none;
    }
    
    #Home {
      background-color: red;
    }
    
    #Game { background-color: green;}
    
    #Contact {
      background-color: blue;
    }
    
    #About {
      background-color: Yellow;
    }
    
    body {
      background-image: url('help.jpg');
      background-repeat: no-repeat;
      background-attachment: fixed;
      background-size: cover;
    }
    
    input {
      top: 400px;
      right: 330px;
      width: 18%;
      height: 6%;
      position: absolute;
    }
    
    button {
      width: 10%;
      height: 6%;
      position: absolute;
      font-family: Arial;
      top: 400px;
      right: 120px;
      text-align: center;
      font-size: 25px;
      color: white;
      border: none;
      outline: none;
      cursor: pointer;
      border-radius: 5px;
      background-color: #000208;
    }
    
    button:hover {
      transition: 0.05s;
      background-color: #0B4870;
      transform: rotateZ(-5deg);
      box-shadow: 0 0 30px -10px #0B4870;
    }
    
    button:active {
      transform: translateY(20px);
      transform: rotateZ(5deg);
    }
    
    button2 {
      width: 5%;
      height: 6%;
      position: absolute;
      font-family: Arial;
      top: 400px;
      right: 300px;
      text-align: center;
      font-size: 40px;
      color: white;
      border: none;
      outline: none;
      cursor: pointer;
      border-radius: 5px;
      background-color: #000208;
    }
    
    button:hover {
      transition: 0.05s;
      background-color: #0B4870;
      transform: rotateZ(-5deg);
      box-shadow: 0 0 30px -10px #0B4870;
    }
    
    button:active {
      transform: translateY(20px);
      transform: rotateZ(5deg);
    }
    
    p1 {
      width: 30%;
      height: 10%;
      position: absolute;
      top: 300px;
      right: 110px;
      font-family: Arial;
      text-align: center;
      font-size: 60px;
      color: white;
      border: none;
      outline: none;
      border-radius: 5px;
      background-color: #000208;
    }
    
    p {
      width: 20%;
      height: 10%;
      position: absolute;
      top: 450px;
      right: 300px;
      font-family: Arial;
      text-align: center;
      font-size: 30px;
      color: white;
      border: none;
      outline: none;
    }
  </style>
</head>

<body>
  <button4 class="tablink" onclick="openPage('Home', this, 'red')" style="">Home</button4>
  <button4 class="tablink" onclick="openPage('Game', this, 'green')" id="defaultOpen" style="background-color: green;">Game</button4>
  <button4 class="tablink" onclick="openPage('Contact', this, 'blue')" style="">Contact</button4>
  <button4 class="tablink" onclick="openPage('About', this, 'yellow')" style="">About</button4>

  <div id="Home" class="tabcontent" style="display: none;">
    <h1>Home</h1>
 

    <p>Click the button to sort the table numerically:</p>
    <p2><button onclick="sortTable()">Sort</button></p2>

    <table id="myTable">
      <tr>
        <th>ID</th>
        <th>Name</th>
      </tr>
      <tr>
        <td>
          <p6>
            <div id="total-score">0</div>
          </p6>
        </td>
        <td>Berglunds snabbkop</td>
      </tr>
      <tr>
        <td>3</td>
        <td>North/South</td>
      </tr>
      <tr>
        <td>6</td>
        <td>Alfreds Futterkiste</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Koniglich Essen</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Magazzini Alimentari Riuniti</td>
      </tr>
      <tr>
        <td>7</td>
        <td>Paris specialites</td>
      </tr>
      <tr>
        <td>4</td>
        <td>Island Trading</td>
      </tr>

    </table>

    <script>
      function sortTable() {
        var table, rows, switching, i, x, y, shouldSwitch;
        table = document.getElementById("myTable");
        switching = true;
        /*Make a loop that will continue until
        no switching has been done:*/
        while (switching) {
          //start by saying: no switching is done:
          switching = false;
          rows = table.rows;
          /*Loop through all table rows (except the
          first, which contains table headers):*/
          for (i = 1; i < (rows.length - 1); i++) {
            //start by saying there should be no switching:
            shouldSwitch = false;
            /*Get the two elements you want to compare,
            one from current row and one from the next:*/
            x = rows[i].getElementsByTagName("TD")[0];
            y = rows[i + 1].getElementsByTagName("TD")[0];
            //check if the two rows should switch place:
            if (Number(x.innerHTML) > Number(y.innerHTML)) {
              //if so, mark as a switch and break the loop:
              shouldSwitch = true;
              break;
            }
          }
          if (shouldSwitch) {
            /*If a switch has been marked, make the switch
            and mark that a switch has been done:*/
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
          }
        }
      }
    </script>

  </div>

  <div id="Contact" class="tabcontent" style="display: none;">
    <h1>Contact</h1>
    <p>Get in touch, or swing by for a cup of coffee.</p>
  </div>

  <div id="About" class="tabcontent" style="display: none;">
    <h1>About</h1>
    <p>Who we are and what we do.</p>
  </div>

  <div id="Game" class="tabcontent" style="display: block;">
    <div id="Game" class="tabcontent" style="display: none;">
      <h1>Game</h1>
      <p>Some Game this fine day!</p>
    </div>

    <canvas id="myCanvas" width="800" height="500" style="border:80px solid #ffffff;"></canvas>

    <p style="width: 300px; vertical-align:top"></p>
    <p1 id="message001">What is <text id="name001">6-8</text>?</p1>

    <div id="disappear001"><input type="text" id="input001" autofocus=""></div>
    <div id="disappear002"><button onclick="submit001()">Submit</button></div>

    <p id="answer001"></p>
    <p3 id="button001"></p3>
    <p3 id="button002"></p3>




    <script type="text/javascript">
      function openPage(pageName, elmnt, color) {
        var i, tabcontent, tablinks;

        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
          tabcontent[i].style.display = "none";
        }

        tablinks = document.getElementsByClassName("tablink");
        for (i = 0; i < tablinks.length; i++) {
          tablinks[i].style.backgroundColor = "";
        }

        document.getElementById(pageName).style.display = "block";
        elmnt.style.backgroundColor = color;
      }
      // Get the element with id="defaultOpen" and click on it
      document.getElementById("defaultOpen").click();

      var question001 = ["6-8", "10/2", "3+7", "5-3", "6+5", "7-4"];
      var answer001 = ["-2", "5", "10", "2", "11", "3"];
      var random001 = Math.floor(Math.random() * question001.length);

      function submit001() {
        var b = input001.value;

        if (random001 == 0 && b == answer001[0]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 1 && b == answer001[1]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 2 && b == answer001[2]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 3 && b == answer001[3]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 4 && b == answer001[4]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 5 && b == answer001[5]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 6 && b == answer001[6]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";

        } else {
          document.getElementById("answer001").innerHTML = "Game Over";
          document.getElementById("button002").innerHTML = "<button onclick=window.location.reload()>Reset</button>";
          document.getElementById("disappear002").innerHTML = "";
          gameOver();
        }
      }

      document.getElementById("name001").innerHTML = question001[random001];

      function btn001() {
        random001 = Math.floor(Math.random() * question001.length);
        document.getElementById("name001").innerHTML = question001[random001];
        document.getElementById("button001").innerHTML = "";
        document.getElementById("disappear001").innerHTML = "<input type=text id=input001 autofocus>";
        document.getElementById("disappear002").innerHTML = "<button onclick=submit001()>Submit</button>";
        document.getElementById("answer001").innerHTML = "";
      }

      function question() {
        return document.getElementById("message001").textContent;
      }

      let canvas = document.getElementById("myCanvas");
      let context = canvas.getContext("2d");
      context.font = '30px arial';
      let scrollCounter, cameraY, current, mode;
      let total_score = document.querySelector('#total-score');
      let ySpeed = 5;
      let height = 50;
      let boxes = [];

      boxes[0] = {
        x: 300,
        y: 200,
        width: 200
      };
      let debris = {
        x: 300,
        width: 0
      };

      function newBox() {
        boxes[current] = {
          x: 300,
          y: (current + 10) * height,
          width: boxes[current - 1].width
        };
      }

      function gameOver() {
        mode = 'gameOver';
        context.fillText('Your tower collapsed! Wanna play again?', 200, 40);
        total_score.innerHTML = parseInt(total_score.innerHTML) + current - 1;
      }

      function animate() {
        if (mode != 'gameOver') {
          context.clearRect(0, 0, canvas.width, canvas.height);
          context.fillText('Score: ' + (current - 1).toString(), 20, 40);
          for (let n = 0; n < boxes.length; n++) {
            let box = boxes[n];
            context.fillStyle = 'rgb(' + n * 14 + ',' + n * 23 + ',' + n * 25 + ')';
            context.fillRect(box.x, 600 - box.y + cameraY, box.width, height);

          }
          context.fillStyle = 'white';
          context.fillText(question(), 310, 440);
          context.fillRect(debris.x, 600 - debris.y + cameraY, debris.width, height);
          if (mode == 'bounce') {
            boxes[current].x = boxes[current].x + xSpeed;
            if (xSpeed > 0 && boxes[current].x + boxes[current].width > canvas.width)
              xSpeed = -xSpeed;
            if (xSpeed < 0 && boxes[current].x < 0)
              xSpeed = -xSpeed;
          }
          if (mode == 'fall') {
            boxes[current].y = boxes[current].y - ySpeed;
            if (boxes[current].y == boxes[current - 1].y + height) {
              mode = 'bounce';
              let difference = boxes[current].x - boxes[current - 1].x;
              if (Math.abs(difference) >= boxes[current].width) {
                gameOver();
              }
              debris = {
                y: boxes[current].y,
                width: difference
              };
              if (boxes[current].x > boxes[current - 1].x) {
                boxes[current].width = boxes[current].width - difference;
                debris.x = boxes[current].x + boxes[current].width;
              } else {
                debris.x = boxes[current].x - difference;
                boxes[current].width = boxes[current].width + difference;
                boxes[current].x = boxes[current - 1].x;
              }

              current++;
              scrollCounter = height;
              newBox();
            }
          }
          debris.y = debris.y - ySpeed;
          if (scrollCounter) {
            cameraY++;
            scrollCounter--;
          }
        }
        window.requestAnimationFrame(animate);
      }

      function restart() {
        boxes.splice(1, boxes.length - 1);
        mode = 'bounce';
        cameraY = 0;
        scrollCounter = 0;
        xSpeed = 0;
        current = 1;
        newBox();
        debris.y = 0;
      }

      document.getElementById("disappear002").onclick = function() {
        if (mode == 'gameOver')
          restart();
        else {
          if (mode == 'bounce')
            mode = 'fall';
        }
      };

      restart();
      animate();
    </script>

  </div>
  <div class="as-console-wrapper">
    <div class="as-console"></div>
  </div>

</body>

</html>

_x000D_

_x000D_

_x000D_

Solution

Your first row will fail for Number(x.innerHTML) when you lopping in sortTable(), and will result NaN.

<td>
      <p6>
        <div id="total-score">0</div>
      </p6>
    </td>

Modify it to

 <td id="total-score"> 0
        </td>
Answered By: Anonymous

Related Articles

  • How do I keep only the first map and when the game is…
  • how to use canvas in JavaScript flappy bird code
  • How to properly do JSON API GET requests and assign output…
  • Active tab issue on page load HTML
  • Undefined reference to 'vtable for ✘✘✘'
  • How do i update a javascript variable as its value changes?
  • Is it possible to apply CSS to half of a character?
  • Why my "title" bloc doesn't go to bottom?
  • Having trouble with my nav bar/header, It used to work but…
  • How to use html template with vue.js

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I get the “id” value with BeautifulSoup?

Next Post:

Converting a dictionary to string, then back to dictionary again

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error