0

I am a little confused regarding varable scope. The below code does not execute the playerDetails function properly - UNLESS I declare the variable 'panel' inside the function block.

However - I thought if a variable was declared outside of a function block it therefore has global scope - and is visible to all function blocks.

In short - I can get the code to work by moving the first line into the playerDetails function block - I just don't see why I should need to do that. Any help would be much appreciated.

Thanks. Code below ;

var panel = document.getElementById ( "panel" ) ;

function init()
{
var player1 = {name: "DJCraigo" , score: 178242 , rank: "1st"} ;
var player2 = {name: "Tohny" , score: 155522 , rank: "2nd"} ;
player1.showDetails = playerDetails ;
player2.showDetails = playerDetails ;

player2.showDetails() ;

player1.showDetails() ;
}

function playerDetails()
{
  panel.innerHTML += "Player with name " + this.name + " is ranked " + this.rank + " with a         score of " + this.score + "<br>" ;
}
document.addEventListener ( "DOMContentLoaded" , init , false ) ; 
4
  • 4
    The DOM is probably not yet ready at the time you issue getElementById("panel"). You should bind this operation to DOMContentLoaded the same way you do for the init() function. Commented Oct 15, 2013 at 7:49
  • Just put your JavaScript within the <body> tag. Commented Oct 15, 2013 at 7:51
  • see stackoverflow.com/a/1471738/891338 Commented Oct 15, 2013 at 7:53
  • frederic - how do i do this please? Commented Oct 15, 2013 at 16:48

1 Answer 1

1

The line with the declaration / initialization of panel variable gets executed just when it is read. And the DOM is probably not initialized, so, getElementById does not return anything.

If you want your variable to be global, declare it as you are doing, but initialize (getElementById) inside the init function.

var panel;
function init()
{
    panel = document.getElementById ( "panel" ) ;
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.