75

I have a function that strips the youtube id off a url. I then want to use this function 10 time per page (in the wordpress loop).

The function works great when I feed it the url within my function script tags, but when I start a new set of script tags within the loop, it does not work.

I need to know how I can use my function without declaring it all first.

So this is the code I have in the header:

 <script type="text/javascript"> 
$(document).ready(function() {
var getList = function(url, gkey){
        var returned = null;
        if (url.indexOf("?") != -1){
          var list = url.split("?")[1].split("&"),
                  gets = [];

          for (var ind in list){
            var kv = list[ind].split("=");
            if (kv.length>0)
                gets[kv[0]] = kv[1];
        }

        returned = gets;

        if (typeof gkey != "undefined")
            if (typeof gets[gkey] != "undefined")
                returned = gets[gkey];

        }

            return returned;

    };


        // THIS WORKS

    alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));


      });

But when I try use this somewhere else on the page, it doesnt work.

 <script type="text/javascript"> 

      $(document).ready(function() {
              alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
      };
      </script>

Firebug gives me getList is not defined which makes sense, because its not. Am I able to 'globally' declare this function?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
wesbos
  • 25,839
  • 30
  • 106
  • 143
  • Sorry for the poor formatting, every time I edit the code, it turns out weird. The code is valid. – wesbos Feb 08 '10 at 17:00
  • One thing BTW - declaring it inside document.ready means it's defined only when document is ready (after page is loaded) so you should call the function when you're sure it's defined. Declaring it as a global object may not be enough if the declaration itself is run after you trying to use it. – Tomasz Struczyński Sep 05 '11 at 10:09

6 Answers6

109

You have two options, add it to the window object to make it global:

window.getList = function(url, gkey){ 
    // etc...
}

or move it from inside the document ready event handler into the global scope:

$(document).ready(function() {  
    alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
});  
var getList = function(url, gkey){  

    var returned = null;  
    if (url.indexOf("?") != -1){  
      var list = url.split("?")[1].split("&"),  
              gets = [];  

      for (var ind in list){  
        var kv = list[ind].split("=");  
        if (kv.length>0)  
            gets[kv[0]] = kv[1];  
    }  

    returned = gets;  

    if (typeof gkey != "undefined")  
        if (typeof gets[gkey] != "undefined")  
            returned = gets[gkey];  

    }  

        return returned;  

};  

You might also want to read this question about using var functionName = function () {} vs function functionName() {}, and this article about variable scope.

Community
  • 1
  • 1
Andy E
  • 338,112
  • 86
  • 474
  • 445
46

Yet another option is to hang the function off the jQuery object itself. That way you avoid polluting the global name space any further:

jQuery.getlist = function getlist(url, gkey) {
  // ...
}

Then you can get at it with "$.getlist(url, key)"

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks to you, just made my first jQuery function, awesome! If there's a more comprehensive resource to make your own jQuery functions, please let me know, but this helped me http://blogs.microsoft.co.il/blogs/basil/archive/2008/09/22/defining-your-own-functions-in-jquery.aspx – PJ Brunet Jun 15 '13 at 21:19
8

declare getList() outside the ready() function..

var getList = function(url, gkey){
        var returned = null;
        if (url.indexOf("?") != 
....
....
...
};

Now the getList will work anywhere in the code:

$(document).ready( function() {
alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
});

The problem was, scope of the getList(.) function.

coolest_head
  • 1,388
  • 1
  • 7
  • 6
5

You can simply add your function in the $.fn variable:

(function ($) {

   $.fn.getList = function() {
       // ...
   };

}(jQuery));

Example usage:

$().getList();

This is what you would typically do while creating a Basic Plugin for jQuery.

milkovsky
  • 8,772
  • 4
  • 28
  • 32
2

Just define it as a regular function at the top of your script:

<script type="text/javascript">
    function getlist(url, gkey){  
        ...
    }
</script>
Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
  • Regardless that is true but it's not a good solution for example in that case you defined jQuery function in other page header and you want to use it inside img element as onclick="$.Function()", Other answers must be better. – QMaster Jun 27 '15 at 09:26
  • 1
    Not sure I understand your comment (and downvote). This code answers the question of how to create a function in the global namespace - outside of the jQuery handler. – Traveling Tech Guy Jun 27 '15 at 18:48
  • Globally word point it's meaning [Globally]. I assume the global function accessible from every java script section but that's not true when you just define at top of scripts. I mentioned a sample of {inside img element as onclick="$.Function()"}. After all the down vote is just for helping user to determine the best answer. Sincerely. – QMaster Jun 28 '15 at 07:57
-4

To declare it as a global function, just get rid of all the jQuery specific bits. Something like this:

function getList(url, gkey) {
    var returned = null;
    if (url.indexOf("?") != -1){
    var list = url.split("?")[1].split("&"), gets = [];
    for (var ind in list){
        var kv = list[ind].split("=");
        if (kv.length>0) {
            gets[kv[0]] = kv[1];
        }
    }

    returned = gets;

    if (typeof gkey != "undefined") {
        if (typeof gets[gkey] != "undefined") {
            returned = gets[gkey];
        }
    }

    return returned;
}

And then you should be able to call it from anywhere.

Farinha
  • 17,636
  • 21
  • 64
  • 80
  • This makes no sense. If he used jQuery, it was for a reason so why not using it anymore? What's more - declaring something in $(document).ready event ensures you that the whole page is loaded, which is sometimes essential. Of course, mixing document.ready declaration with calling function outside of this scope might be bad, but simply removing jQuery call is not exactly a solution. You should at least explain why removing jquery is good. – Tomasz Struczyński Sep 05 '11 at 10:03
  • 3
    UPDATE: ok, I got carried up, your answer is actually not so bad. But what it lacks is an explanation what are the benefits and dangers of moving it outside document.ready scope, the differences vetween var x = function(...) and function x(...) declarations and so on. Without it it's somehow like magic - solves one specific problem, but without knowledge why it works. – Tomasz Struczyński Sep 05 '11 at 10:12