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>
  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Popular Posts

Alternatively, you may want to return to the Home Page to view the most recent blog posts in order. If you have any questions, I make a point of reading and responding to all comments. Thanks for joining!

  • this is cool thanks for sharing this one it really makes my life easier in coding it I learned a lot from this
  • Tsiou
    Thanks a lot! This saved me a lot of time and frustration :)
  • Vinicius Spader
    Good post, but I think is simplier than that (at least is working for me).

    html file


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

    tilex.js

    $("document").ready(function (){
    $("body").append("See? It Works");
    });

    Am I right?
  • Ibergeckos
    You're a life saver
  • Muthu
    Thank a lot , the post was quite simpler in explaining the stuff without any messy codes around the concept.. ( i was trying for past 1 hour without noticing that the thing

    src="js/jquery-1.3.2.min.js"> 
    .. finally changed it to 
    <script src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
    google.load("jquery", "1.3.2");

      and now it works.. thank you..</script>
  • Cleverson
    THANKSSSSSS A LOTTTT
  • Rockey
    Hello, this example seems to work for non-IE browser. Does anyone have a workaround for IE ?
  • Kueyiar
    how did you manage to get it to work? I'm going crazy trying to, currently using firefox
  • Brett
    I wrote this a long time ago when I was more novice at JS. This is actually a better resource:

    http://snook.ca/archives/javas...
  • Doug McDonald
    Thanks for this post, it was indeed helpful, it should probably be noted that you can achieve the same thing via this syntax:

    var tile = function() {

    //do stuff

    };

    Hope it helps, Doug
  • Jos
    I have this function that I want to put in a separate js document to keep my HTML page clean, but it's not working. Could you please help? :(

    <script type="text/javascript">
    $(document).ready(function() {

        //When page loads...
        $(".thumbCategory").hide(); //Hide all content
        $("ul.tabsCont li:last").addClass("current").show(); //Activate last tab
        $(".thumbCategory:last").show(); //Show last tab content - cause using right float -reversing

        //On Click Event
        $("ul.tabsCont li").click(function() {

            $("ul.tabsCont li").removeClass("current"); //Remove any "active" class
            $(this).addClass("current"); //Add "active" class to selected tab
            $(".thumbCategory").hide(); //Hide all tab content

            var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
            $(activeTab).fadeIn(500); //Fade in the active ID content
            return false;
        });

    });
    </script>
  • Jonneyhall7979
    Hi, thanks for the post. but Im still having a problem trying to make this work. I put in the info you post but it dose not respond. Is there by any chance you can set up a demo or something we can actually see the physical code......thanks!
  • Jonneyhall7979
    Hey, Got it to work......Thanks
  • Kueyiar
    hey buddy, how did you get it to work, I'm unable to get it to work
  • thanks for this post! also placing
    $(document).ready(function(){
    into the external file seems to work fine...
  • brianb
    Thank you! I was up till 3am looking for this info. Then I changed my Google search from things like "jQuery with Javascript" and "jQuery in Javascript" to "jQuery in external file" and BINGO this post came up. Let me go to sleep in peace. :-)
  • Rasel
    many thanks for this post....
  • Antony
    im new to jquery and im not sure if this is what i am looking for.

    i currently have a HTML page with certain jquery functions running (sliders etc)

    now its clogging up my HTML page quite a bit having all functions under each part.

    i want to be able to place all my jquery functions in a separate java-script file which i can link to the page in the

    is this the solution for that?
  • Good Artical, Thx
    http://www.springtec.net
  • jasonorf
    Hi Thanks for the tut. One problem im having is when i add multiple functions to the ready(). Its throwinf out my entire page. Any ideas why ?

    With one function its fine but with multiple.....

    Thanks heaps
  • Eric
    (function($){
    functionA = function(){
    //stuff happens
    };

    functionB = function(){
    //stuff happens
    };

    })(iQuery);
  • Anon
    Just wanted to say a very BIG "Thank You".

    I've looked around for ways to move my JQuery content from the HTML file to their own JQuery Files - and failed to get them to work.
    This simple little page got it working easily.

    Keep up the good work.
blog comments powered by Disqus