Tutorial :Javascript method not defined



Question:

Why does this not work when I move the code in the first script block (without the script tag itself) to an external javascript file.

The idea is to call homead.load() from home page and load everything processed by homead_build();

Error says 'homead not defined' using Firefox Error console

<div id="box">  </div>    <script type="text/javascript">      var homead = {          box_id: "box",          width: "150px",          load: function(){          homead.homead_build();          },            homead_build: function(){              var div = document.createElement('div');              div.style.width = homead.width;              div.style.height = '55px';              div.style.border = 'solid 2px #000';              var box = document.getElementById(homead.box_id);              box.appendChild(div);          }      };  </script>    <script language="JavaScript" type="text/javascript">       homead.load();  </script>  


Solution:1

Maybe you are including the external script file after you call homead.load()? Make sure it is loaded before it is used:

<script language="JavaScript" type="text/javascript" src="external.js"></script>  <script language="JavaScript" type="text/javascript">       homead.load();  </script>  


Solution:2

Make sure you include it before using homead, and that the file has been loaded correctly. (e.g.: say alert("im loaded...") in the file)

Your code can be simplified btw:

var homead = {      box_id: "box",      width: "150px",      load: function(){          var div = document.createElement('div');          div.style.width = homead.width;          div.style.height = '55px';          div.style.border = 'solid 2px #000';          var box = document.getElementById(homead.box_id);          box.appendChild(div);      }  };  


Solution:3

yes its working fine.You might be giving wrong src path of file to script tag.

I have done following ;

 <script language="JavaScript" type="text/javascript" src="../../Scripts/test.js" ></script>  

added code

    <div id="box">  </div>      <script language="JavaScript" type="text/javascript">       homead.load();  </script>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »