How do I call javascript functions in html? -


i understand different ways can call javascript function in html. have following code:

html:

<body>     <div id="container">         <canvas height="600" width="600" id="mycanvas">         </canvas>     </div>     <script type="text/javascript" src="js/code.js"></script> </body> 

js:

//constructs ball , snake before game starts function init() {     var thecanvas = document.getelementbyid("mycanvas");     var context = thecanvas.getcontext("2d");     context.fillstyle = "#ffa23f";     context.fillrect(10,10,10,10); }  window.addeventlistener('load',init(),false); 

1) in js code had code init() method through event listener, understand it's 1 of way invoke js method (through events). why cant call init() method without event listener? can call in html calling init()? this:

<body>     <div id="container">         <canvas height="600" width="600" id="mycanvas">               <script>                      init();               </script>         </canvas>     </div>     <script type="text/javascript" src="js/code.js"></script> </body> 

2) why when remove function heading able execute javascript code automatically having script tags , src js file? in js:

    var thecanvas = document.getelementbyid("mycanvas");     var context = thecanvas.getcontext("2d");     context.fillstyle = "#ffa23f";     context.fillrect(10,10,10,10); 

3) other ways of calling js methods in html? best practices? there other ways in can call javascript methods in html?

you can call function after html loads, preferably in footer below.

//put function anywhere, either in header or footer function init() {     var thecanvas = document.getelementbyid("mycanvas");     var context = thecanvas.getcontext("2d");     context.fillstyle = "#ffa23f";     context.fillrect(10,10,10,10); } 

put code in footer, when run, elements specified in js in dom

init() 

another way

you can call in body tag in onload event, below

<body onload="init()" > 

Comments