7

i want to put my javascript code in head instead of body, but because the head loads before the body section in the html document, my code becomes useless as all selectors become undefined.

in jquery i can use $(document).ready to overcome this problem, however i dont want to use jquery and i'm wondering if there's a solution for this in javascript.

i tried:

if(document.readyState === "complete") {/*my javascript code */}

and

window.onload = function(){/*my javascript code */}

but both doesn't work, any suggestions? thanks in advance.

HTML:

<div id="section" onClick="shout()">test</div>

JAVASCRIPT:

window.onload=function(){
function shout(){
var str = document.getElementById("section").innerHTML;
alert(str);
}
}
Funk Forty Niner
  • 73,764
  • 15
  • 63
  • 131
  • 3
    And `window.onload` should suffice, so if you want help debugging it, you'll need to provide a complete example. Look for errors in the browser's JavaScript console, to start. – Matt Ball Mar 23 '13 at 14:45
  • 1
    i updated my question, the code above return shout is undefined –  Mar 23 '13 at 15:01
  • 1
    @mike: That's because `shout` is not global and therefore cannot be found by the inline event handler. There is no need to define the function inside the `load` event handler in this case. Have a look at [my answer here](http://stackoverflow.com/a/9657629/218196) which explains a little in which situations you need to listen for `load` and `ready` events. – Felix Kling Mar 23 '13 at 15:05
  • thanks Felix, it worked after moving `shout` outside `load` event handler. your answer linked in your comment is very helpful, cheers. –  Mar 23 '13 at 15:26

0 Answers0