mally
mally

Reputation: 295

Spelling game score points using javascript

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>

Upvotes: 1

Views: 1247

Answers (1)

MultiplyByZer0
MultiplyByZer0

Reputation: 7119

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; 
    }
}

Upvotes: 3

Related Questions