Kousha
Kousha

Reputation: 36189

jQuery initialize functions before using

I want to have a statement as

$(myVar).click(function(){
    // Do some stuff
});

This statement is in the main .js file that is included on every page. I want to then have myVar defined in different files on different pages and then the statement above becomes active.

How do I do that?

Upvotes: 0

Views: 82

Answers (7)

Nicholas Hazel
Nicholas Hazel

Reputation: 3750

Define it like this instead...

$(myVar).on('click', function(){
    // Do whatever
});

And call that handler in your document using:

<script>var myVar=yourValue;</script>

<script src="myJs.js"></script>

If you do it this way, you will ensure your var is loaded before your script that relies on it and your DOM will carry out its merry way.

FYI - There is no real way to share a variable between multiple pages unless you define a default in your myJs.js file or create a global variable per HTML doc.

Upvotes: 2

zzlalani
zzlalani

Reputation: 24344

In main.js add this function rather..

var myVarClick = function (ele) {
    // Do some stuff
    alert(ele.val());
}

and in each page call this function..

$("button").click(function () {
    myVarClick($(this));
});

Upvotes: 0

Ryker.Wang
Ryker.Wang

Reputation: 797

var myVar=$("#id");
myVar.click(function(){
    // Do some stuff
});

Upvotes: 0

James Hibbard
James Hibbard

Reputation: 17725

If I understand you correctly you can just the following:

Page 1

var myVar = $("#myElement");
<script src="main.js" type="text/javascript"></script>

Page 2

var myVar = $(".myElements");
<script src="main.js" type="text/javascript"></script>

Upvotes: 1

hemanth
hemanth

Reputation: 1043

Try initializing myVar before you load main.js

var myVar = "whatever";
<script src="main.js" type="text/javascript"></script>

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Include the file that has the declaration of myVar before the script that uses it:

<script type="text/javascript" src="myVarSource.js"></script>
<script type="text/javascript" src="doStuffSource.js"></script>

Upvotes: 0

TGH
TGH

Reputation: 39248

You can define myVar before you include main.js

var myVar = "someThing";

--include main.js

Upvotes: 0

Related Questions