So as i'm new to coding, i decided to make a "snake" game. for those who dont know you are a snake and you go on a grid and random food pops up. when you eat the food your tail becomes longer and and longer and you cant hit the walls or yourself. it worked fine and i was so proud but upon trying to add a scoreboard to the game i've become lost. in my index.HTML i added a DIV and a variable using and it displayed on the screen fine. what i cant figure out how to do is how to change the variable of the score from the javascript. my instinct was to go to where i had the code for "when you eat the food, you become longer" and add "also change score" but id need to update the index.HTML to do that. I named the variable "scoreVar" in my index.HTML and in the javascript i tried document.getElementById(scoreVar).innerHTML and tried updating the score by one but it wouldnt work. i asked people and searched online but nothing came up. PLEASE HELPPPPP!! thanks! :D
Asked
Active
Viewed 52 times
-3
-
1Don't tell stories. Show us the code and explain what is not working with the code. See also [How to ask questions](http://stackoverflow.com/help/how-to-ask) – NineBerry Nov 01 '16 at 01:58
-
Possible duplicate of [Global variables in Javascript across multiple files](http://stackoverflow.com/questions/2932782/global-variables-in-javascript-across-multiple-files) – NineBerry Nov 01 '16 at 02:10
-
please make a [fiddle](https://jsfiddle.net/) and put your working code in there so we can see what you have done till now and what is the problem. bu the way, you have `document.getElementById(scoreVar).innerHTML`, so what is exactly in the `scoreVar` variable? the score number? if so, you can not access the score element in your `html` by this code. you have to use the `ID` of the `div` which you created for the score... – EhsanT Nov 01 '16 at 03:53
1 Answers
0
If you declare variables outside of functions, these are global variables that you can access from anywhere just by their name. Consider this simple example.
A html file
<html>
<head>
<script>
var myCounter = 0;
</script>
<script src="file.js"/></script>
</head>
<body>
<div>Hello World!</div>
<button onclick="alert(myCounter);">Show counter value</button>
<button onclick="IncreaseCounter();">Increase counter value</button>
</body>
</html>
The referenced file.js
function IncreaseCounter()
{
myCounter++;
}

NineBerry
- 26,306
- 3
- 62
- 93
-
hmmmm, are you sure this answer is for this question?! because his question is not related to the scopes but it's related to how to modify DOM... – EhsanT Nov 01 '16 at 03:50
-
@EhsanT Well, yeah, hard to tell, because the question is so verbose and confusing and has no code... – NineBerry Nov 01 '16 at 03:56