Separating jQuery Functions into External Files (without selectors!)

In javascript, writing reusable blocks of code is easy. You simply enter something like: “function myFunction() { … }”, and then you later call it by simply writing “myFunction();”. Consequently, when I write jQuery, I often use this javascript shorthand within my jQuery ready tags. As long as all the code stays in a single file, things go smoothly.

But sometimes code grows, and when it does, you’ve got to separate your logic into separate external js files. That’s when things break. You see, in each of these external files, you now have to separately reiterate the jQuery ready tags, and when you do, you’ve buried your functions in a (jQuery) function, rendering it hidden. Out of scope. Or as the error console will tell you, “Missing”.

The trick is to create a jQuery function. There are articles all over the place that tell you how to do this. But every one that I’ve found seems to assume that you want your function to act on a selector. What I needed (and you may as well), was a function that acted just like that regular old javascript function (with jQuery syntax enabled). Believe it or not, all it takes is a minor tweek. Check it out:

External File (tilex.js):

  (function($){
    tile = function() {
      $("body").append('See? It works.');
    };
  })(jQuery);

Inline HTML:

<!DOCTYPE html>
<html>
<head>
<title>HyperStudio Timeline</title>
  <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
  <script type="text/javascript" src="js/tilex.js"></script>

  <script type="text/javascript">
   $(document).ready(function(){
      tile();
    });
</script>
</head>
<body>
</body>
</html>