I'm trying to offload common functions to a separate functions.js file in order to clean things up. I've managed success in making the global functions work, but there's some inconsistency in the way that I need to write and call the function that is confusing me.
One of my global functions:
$.getTld = function() {
var tld = document.location.hostname.split('.').pop();
return tld;
};
I can call it like this from another JS file:
$.setPersonaCookie = function(name, value, days) {
$.cookie(name, value, {
expires: days, // Expires in 360 days
path: '/', // Is on the default path
domain: 'mydomain.' + $.getTld(), // The value of the domain attribute of the cookie
secure: $.getProtocol() // set secure cookies - setting in htaccess
});
return;
};
In my same functions.js file I've set up another function in the same way as I did with the $.getTld function:
$.getQueryVariable = function(name, url) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
};
And I'm calling the function like this:
$(document).getQueryVariable('q');
But, I get a console error indicating that $.getQueryVariable is not defined. In order to make it work, I have written the function like this instead:
$.fn.getQueryVariable = function(name, url) {...};
When written this way, I can successfully call the function.
So, why do I need to add the extra .fn to the getQueryVariable function to make this work as a global function?