tags:

views:

31

answers:

2

This doesn't work in my browser - is this normal? It only works when I declare the alias for the document Object inside the function someFunc scope.

var pic1 = document.getElementById('pic1');

var someFunc = function () {

    pic1.style.left = "100px"; 
}
A: 

Yes. You just need to ensure you are calling someFunc after the pic1 element has loaded on page. On that note, it's best practice to put you JavaScript at the bottom right before the closing body tag.

Check your code out in action - http://jsfiddle.net/dga9k/1/

Jason McCreary
The standard specifies that script goes in the head section, so that would be what's best practice. There are different reasons to put script in the body, but that should not be the first option.
Guffa
Excellent Example, thank you! Strangly in my app it does not work. I will do some more testing.
Stephan Kristyn
@Guffa, comment back with the line from the HTML spec stating that `script` goes in the head. I understand this is *common* practice. Yet, in my 10 years of web development, I have neither come across this in the spec nor had the W3C validator error or warn.
Jason McCreary
@Crescent Fresh @Oded of course the pic1 element is defined in HTML. @Guffa I put the JS code in an external file, that is what I consider as best practice. I did some testing in my app and it was indeed a racing condition and the JS code outside the someFunc function got invoked before the HTML element got loaded. The alert consequently threw back [null] instead of [object HTMLDivElement]. Sharp and helpful answers, thank you.
Stephan Kristyn
+1  A: 

It's not a scope problem. The probable reason is that you are trying to get the reference to the element before the element has been created. You have to wait until the element has loaded before you can access it, for example using the onload event:

<html>
<head
<title>Test</title>
<script>

function init() {

  var pic1 = document.getElementById('pic1');

  var someFunc = function () {
    pic1.style.left = "100px"; 
  };

  someFunc();

}

</script>
</head>
<body onload="init();">
<div id="pic1"></div>
</body>
</html>
Guffa