1

I have a spelling game that uses JavaScript.

Currently when the word is spelled correctly it will display a message.

if(++score >= str.length) {
    var text = 'Well done! The correct word is ' + str + '!'
    drawBackground(background, images.back, text);
}

I would like to display one point for each correct word and increment it. This is what i have tried but no luck

function points() {
    var points = 0;    
    if(++score >= str.length) {    
        points++;
        document.getElementById("points").innerText="Score: " + points; 
    }
}

The HTML to display the score

<p>Score: <span id="points"></span></p>
MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
mally
  • 275
  • 2
  • 4
  • 18

1 Answers1

3

Problems with your code:

  • The value of points is being reset to 0 every time you enter the points() function. You must move var points = 0 outside of points(), making it a global variable.
  • As you cannot have a function and a global variable with the same name, you must rename the points variable (e.g. to numPoints).
  • The el.innerText property will only work on IE. Replace it el.textContent.

Improved version of your code:

let numPoints = 0;    

function points() {
    if(++score >= str.length) {    
        numPoints++;
        document.getElementById("points").textContent = "Score: " + numPoints; 
    }
}
MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
  • 2
    I can't tell for sure, but won't `points` inside the function refer to the function itself? – Waleed Khan Dec 31 '13 at 20:14
  • `innerHTML` is not required... `innerText` will work just fine. (If the OP were inserting HTML into the DOM, it would be a different story.) – pete Dec 31 '13 at 20:17
  • @pete That shows exactly how much I understand the DOM. Edited – MultiplyByZer0 Dec 31 '13 at 20:18
  • Also, there is such a thing as `++score` in JavaScript... see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators – pete Dec 31 '13 at 20:19
  • I have just tried this, when I spell the word correct the var text displays from my original code but the score doesn't display. It just says score: – mally Dec 31 '13 at 20:33
  • @MistressDavid Thanks for trying, but i can't get it to work, it must be something I'm missing or not seeing in the previous code. It was made by a freelancer. – mally Dec 31 '13 at 20:53