How can I make a function defined in jQuery.ready available globally?

JavascriptJquery

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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)"

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

<script type="text/javascript">
    function getlist(url, gkey){  
        ...
    }
</script>

Solution 6 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwesbosView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptPointyView Answer on Stackoverflow
Solution 3 - Javascriptcoolest_headView Answer on Stackoverflow
Solution 4 - JavascriptmilkovskyView Answer on Stackoverflow
Solution 5 - JavascriptTraveling Tech GuyView Answer on Stackoverflow
Solution 6 - JavascriptFarinhaView Answer on Stackoverflow