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);
}
}
window.onloadshould 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.shoutis not global and therefore cannot be found by the inline event handler. There is no need to define the function inside theloadevent handler in this case. Have a look at my answer here which explains a little in which situations you need to listen forloadandreadyevents.shoutoutsideloadevent handler. your answer linked in your comment is very helpful, cheers.