0
votes

I have been working on a simple game menu for a game (That I have yet to do.) The code works perfectly in jsfiddle however when I open my local html document none of the javascript works, (console.log and other code works before my error) and I get an error, on my createMenu function: line 67, that says Uncaught TypeError: Cannot read property 'style' of undefined

Here's the code for the createMenu function (also on jsfiddle)

   var menu = document.getElementsByClassName("menu");
var menu2 = document.getElementsByClassName("menu2");
var createMenu = function()
{   
menu[0].style.display = "block";    <---- Error
menu[1].style.display = "block";
menu[2].style.display = "block";
menu2[0].style.display = "none" ;
menu2[1].style.display = "none" ;
menu2[2].style.display = "none" ;

};
createMenu();

Note: I tried to do the display block/none with a loop for less code, but it didn't seem to work at all, not even in jfiddle.

var createMenu = function()
{
    var i = 0;
while (i <3 ) {
    i++;

menu[i].style.display = "block";
menu2[i].style.display = "none" ;
    }
};

Thanks for the help!

1
jsfiddle is set to wrap your code in the onload event. Put simply, menu doesn't exist when your code runs outside of jsfiddle - you need to run it on page load.James Thorpe
Ok ill look up how to that. - not considered duplicate becasue that is jquery and I dont understand jqueryManu
You also have a bunch of JavaScript errors with badly formatted code. Here is the fix that at least runs. jsfiddle.net/7mXPy/34Darren Willows
I think you have the wrong jsfiddle page....Manu
Please don't edit your question when you have a solution, just accept an answer. If you want to comment on the accepted answer, then you can do so with the comment feature rather then by editing your reply into the question.Quentin

1 Answers

2
votes

This is probably because you load your JS code in the head element, meaning the JS is executed before the rendering of your body. You’ll have to either wait for the complete DOM loading or place your script at the end of the body:

         <!-- ... -->
         <script src="your-script.js"></script>
     </body>
</html>