r2dliu
r2dliu

Reputation: 3

Calling function/nested function from external js file

I'm having some issues with running some functions from an external js file.

The html includes:

<script src="js/file.js"></script> 

<script>
    $("#center-button").click(function() {
        explodePage("center"); 
    }); 
</script>

The js file includes:

var explodePage = function(button) {
   //code here
   aboutPage();
}

var aboutPage = function() {
    //code here
}

The explodePage function runs fine, but as soon as it reaches the call to the nested aboutPage function, it starts throwing these uncaught typeerrors at me. It works fine if I don't use an external js file and just put everything into the html. Pretty new to this so probably missing something obvious in scope or something. Any solutions?

Upvotes: 0

Views: 1152

Answers (2)

NiRUS
NiRUS

Reputation: 4259

Declare the function's definition as below:

function explodePage(button) {
   //code here
   aboutPage();
}

function aboutPage() {
    //code here
}

Explanation:

When you use the var keyword for declaring functions, the execution of JS happens as when the variable is initialized, you cannot reference or use variable's before declaration. In contrast with the name function defintion JS interpreter first picks the enclosed functions before execution and initializes it before the code execution. This is called AST- Abstract syntax tree that is followed by JS interpreters.

Also Remember:

Also bind your Jquery code inside a Jquery document ready function, just to make sure the Jquery and the DOM elements are available for the bindings.

Upvotes: 1

Manuel Ro
Manuel Ro

Reputation: 206

It's not a good a idea to pollute the global window object with variables, since there can be collisions. And immediately-invoked function expression is a good solution for this.

(function(){
   //You can declare your functions in here, and invoke them below
   $( document ).ready(function() {
      //Check that the DOM is ready, in order to manipulate it an add events
      $("#center-button").click(function() {
         explodePage("center"); 
      }); 
   });
})($); //Notice that we are injecting a dependency, in this case jQuery

Upvotes: 0

Related Questions