Display javaScript variable value on HTML page?

usman khan :

I write a game java script code i need to display the score variable points in HTML. I try it but it always print 0 and not increment the score. The Score variable is increment by 1 but on HTML page it keep showing 0.Where Should i change in tag to properly display it or should i need to change it java script score function ?

My Java Script code :

var notes = [];
var gameStarted = false;
var Score = 0;

// ==== CLASS FOR ARROWS ==== //

// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the 
// 4. Explode when arrow gets to the bottom

// Class Arrow
function Arrow(direction) {

    // CSS spacings for the arrows //
    var xPos = null;

    switch(direction) {

        case "left" : xPos = "350px";
        break;

        case "up" : xPos = "420px";
        break;

        case "down" : xPos = "490px";
        break;

        case "right" : xPos = "560px";
        break;

    }

    this.direction = direction;
    this.image = $("<img src='./arrows/" + direction + ".gif'/>");
    this.image.css({

        position: "absolute",
        top: "0px",
        left: xPos

    });

    $('.stage').append(this.image);

}// ends CLASS Arrow

// To enable animating the arrows
Arrow.prototype.step = function() {

    // Controls the speed of the arrows
    this.image.css("top", "+=4px");

};

// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {

    // removes the image of the DOM
    this.image.remove();

    // Removes the note/arrow from memory/array
    notes.splice(0,1);

};

// Explodes arrow when hit
Arrow.prototype.explode = function() {

    this.image.remove();

};



// For random arrows
var randNum = 0;

// Frame increasing
var frame = 0;

// Determines the speed of notes
var arrowSpawnRate = 40;


// Random generator for arrows
function randomGen() {

    // Randomizes between 1 and 4
    randNum = Math.floor(Math.random() * 4) + 1;

    if (randNum === 1) {

        notes.push(new Arrow("left"));

    }
    if (randNum === 2) {

        notes.push(new Arrow("right"));

    }
    if (randNum === 3) {

        notes.push(new Arrow("up"));

    }
    if (randNum === 4) {

        notes.push(new Arrow("down"));

    }

}// ends randomGen()


// Render function //
function render() {

    if (frame++ % arrowSpawnRate === 0) {

        randomGen();

    }

    // Animate arrows showering down //
    for (var i = notes.length - 1; i >= 0; i--) {

        notes[i].step();

        // Check for cleanup
        if (notes[i].image.position().top > 615) {

            notes[i].destroy();

        }

    }

}// ends render()



// jQuery to animate arrows //
$(document).ready(function () {

    // shim layer with setTimeout fallback
    window.requestAnimFrame = (function() {

         return window.requestAnimationFrame ||

         window.webkitRequestAnimationFrame ||

         window.mozRequestAnimationFrame ||

         function(callback) {

            window.setTimeout(callback, 40 / 75);

        };

    })();

    /*  place the rAF *before* the render() 
        to assure as close to 60fps with the 
        setTimeout fallback.                    */

    // Infinte loop for game play
    (function animloop() {

        if (gameStarted) {

            requestAnimFrame(animloop);

            render();

        } else {

            window.setTimeout(animloop, 1000); // check the state per second

        }

    })();// ends (function animloop() )


});// ends $(doc).ready



// Listening for when the key is pressed
$(document).keydown( function(event) {

    for (var i = 0; i < notes.length; i++) {

            console.log(notes[i].image.position().top);

        if (event.keyCode == 37 && notes[i].direction == "left") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("LEFT! "+notes[i].explode());

                Score++;
            }

        }
        if (event.keyCode == 38 && notes[i].direction == "up") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("UP! "+notes[i].explode());

                Score++;
            }

        }
        if (event.keyCode == 40 && notes[i].direction == "down") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("DOWN! "+notes[i].explode());

                Score++;

            }

        }
        if (event.keyCode == 39 && notes[i].direction == "right") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("RIGHT! "+notes[i].explode());

                Score++;

            }

        }

    }// ends loop

});// ends $(doc).keyup

function score() {
    document.getElementById("Points").innerHTML = Score;
}

HTML code:

<html>
<head>
    <link rel="icon" href="./arrows/clubbackground.jpg" type="image/gif" sizes="16x16">
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="jsRev.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>DDR-Project 1</title>
</head>
<body>
    <div id="BackgroundScene">
        <div id="DanceScoreboard">
            <div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
                <br><br><br><div class="Status">Click Begin Game to start</div>
            </div>
            <div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
                <div id="Status" class="Status"></div>
            </div>
            <div id="dancePoints" class="Points">Points Earned: <div class="OutputText" id="CorrectCount">0</div>
            </div>
        </div>
        <div class="stage"></div> <!-- ENDS .STAGE -->
        <div id="controls">
            <img id="left" src="./arrows/staticLeft.png">
            <img id="up" src="./arrows/staticUp.png">
            <img id="down" src="./arrows/staticDown.png">
            <img id="right" src="./arrows/staticRight.png">
        </div> <!-- ENDS #CONTROLS -->

</body>
</html>
random :

Call the score function whenever, the Score variable gets updated. In your html there is not element with id Points, however class is present. Instead of document.getElementById("Points").innerHTML = Score; use document.querySelector(".Points").textContent = Score;. No need to use innerHTML, as Score is a number and not an html content.

var notes = [];
var gameStarted = false;
var Score = 0;

// ==== CLASS FOR ARROWS ==== //

// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the 
// 4. Explode when arrow gets to the bottom

// Class Arrow
function Arrow(direction) {
  // CSS spacings for the arrows //
  var xPos = null;

  switch (direction) {
    case "left":
      xPos = "350px";
      break;
    case "up":
      xPos = "420px";
      break;
    case "down":
      xPos = "490px";
      break;
    case "right":
      xPos = "560px";
      break;
  }

  this.direction = direction;
  this.image = $("<img src='./arrows/" + direction + ".gif'/>");
  this.image.css({
    position: "absolute",
    top: "0px",
    left: xPos
  });
  $('.stage').append(this.image);

} // ends CLASS Arrow

// To enable animating the arrows
Arrow.prototype.step = function() {
  // Controls the speed of the arrows
  this.image.css("top", "+=4px");
};

// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {
  // removes the image of the DOM
  this.image.remove();
  // Removes the note/arrow from memory/array
  notes.splice(0, 1);
};

// Explodes arrow when hit
Arrow.prototype.explode = function() {
  this.image.remove();
};



// For random arrows
var randNum = 0;

// Frame increasing
var frame = 0;

// Determines the speed of notes
var arrowSpawnRate = 40;


// Random generator for arrows
function randomGen() {
  // Randomizes between 1 and 4
  randNum = Math.floor(Math.random() * 4) + 1;
  if (randNum === 1) {
    notes.push(new Arrow("left"));
  }
  if (randNum === 2) {
    notes.push(new Arrow("right"));
  }
  if (randNum === 3) {
    notes.push(new Arrow("up"));
  }
  if (randNum === 4) {
    notes.push(new Arrow("down"));
  }
} // ends randomGen()

// Render function //
function render() {
  if (frame++ % arrowSpawnRate === 0) {
    randomGen();
  }

  // Animate arrows showering down //
  for (var i = notes.length - 1; i >= 0; i--) {
    notes[i].step();
    // Check for cleanup
    if (notes[i].image.position().top > 615) {
      notes[i].destroy();
    }
  }
} // ends render()

// jQuery to animate arrows //
$(document).ready(function() {
  // shim layer with setTimeout fallback
  window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      function(callback) {
        window.setTimeout(callback, 40 / 75);
      };
  })();

  /*  place the rAF *before* the render() 
      to assure as close to 60fps with the 
      setTimeout fallback.                    */

  // Infinte loop for game play
  (function animloop() {
    if (gameStarted) {
      requestAnimFrame(animloop);
      render();
    } else {
      window.setTimeout(animloop, 1000); // check the state per second
    }
  })(); // ends (function animloop() )
}); // ends $(doc).ready



// Listening for when the key is pressed
$(document).keydown(function(event) {
  for (var i = 0; i < notes.length; i++) {
    if (event.keyCode == 37 && notes[i].direction == "left") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("LEFT! " + notes[i].explode());
        Score++;
        score();
      }
    }
    if (event.keyCode == 38 && notes[i].direction == "up") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("UP! " + notes[i].explode());
        Score++;
        score();
      }
    }
    if (event.keyCode == 40 && notes[i].direction == "down") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("DOWN! " + notes[i].explode());
        Score++;
        score();
      }
    }
    if (event.keyCode == 39 && notes[i].direction == "right") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("RIGHT! " + notes[i].explode());
        Score++;
        score();
      }
    }
  } // ends loop
}); // ends $(doc).keyup

function score() {
  document.querySelector(".Points").textContent = Score;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="BackgroundScene">
  <div id="DanceScoreboard">
    <div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
      <br><br><br>
      <div class="Status">Click Begin Game to start</div>
    </div>
    <div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
      <div id="Status" class="Status"></div>
    </div>
    <div id="dancePoints" class="Points">Points Earned:
      <div class="OutputText" id="CorrectCount">0</div>
    </div>
  </div>
  <div class="stage"></div>
  <!-- ENDS .STAGE -->
  <div id="controls">
    <img id="left" src="./arrows/staticLeft.png">
    <img id="up" src="./arrows/staticUp.png">
    <img id="down" src="./arrows/staticDown.png">
    <img id="right" src="./arrows/staticRight.png">
  </div>
  <!-- ENDS #CONTROLS -->

Note - Use class names or id names in lower case whenever possible, as minor mistake in casing would make it difficult to identify the error.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31799&siteId=1