I have to write global function in js file that is loaded initially. I want to write function on it so that it can be accessed from all pages. I am new in jquery. I want to know how to write function in js file and call it form other pages?
Asked
Active
Viewed 2.5k times
2 Answers
38
You can add your own jQuery function by doing the following
$.fn.MyFunction = function()
{
//Code here
}
Then inside of another script or the same script, you can run your function by doing $('#myId').MyFunction();
. This is for running the function on an object. The suggestion below is for just running a function.
Adding it to the jQuery object itself:
$.MyFunction = function()
{
//Code here
}
Then call it as $.MyFunction()

Jonathan Hall
- 75,165
- 16
- 143
- 189

Kyle
- 4,421
- 22
- 32
-
Thank you, it helped me. But I have to pass the parameter in function and proceed with that parameter. Any suggestion for this. – haripds Aug 06 '11 at 12:20
-
Sorry it has taken so long to get back to you. Use $.Myfunction = function(arguments) – Kyle Aug 08 '11 at 12:32
-
`$('#myId').MyFunction();` didn't work for me, I had to do `$.fn.MyFunction($('#myId'));`. – Mark Boulder Jul 10 '14 at 15:05
-
@MarkBoulder using `$.fn.MyFunction = function()` will make that function available to all jQuery objects `$('#myId').MyFunction`. If you post a question, I would be happy to take a look. – Kyle Jul 10 '14 at 17:35
-
Yeah, `$.fn.MyFunction = function(container)` works great, but I was only able to access it later on by doing `$.fn.MyFunction($('#myId'));`, not `$('#myId').MyFunction();` as described here. Idk, maybe I'm missing something obvious. Your answer was of tremendous help though, so cheers! – Mark Boulder Jul 10 '14 at 17:52
5
You can define the functions in js file and just include these js files in the pages where you want to use it using script tag.
All the functions defined in the js files will become global and can be used anywhere on the page or in other js files.
<script src="scriptFileName1.js" type="text/javascript"></script>
<script src="scriptFileName2.js" type="text/javascript"></script>

BenMorel
- 34,448
- 50
- 182
- 322

ShankarSangoli
- 69,612
- 13
- 93
- 124