Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global jquery function

Tags:

jquery

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?

like image 548
haripds Avatar asked Aug 05 '11 17:08

haripds


2 Answers

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

like image 174
Kyle Avatar answered Sep 21 '22 19:09

Kyle


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>
like image 26
ShankarSangoli Avatar answered Sep 19 '22 19:09

ShankarSangoli