0

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?

2
  • initialize your variable before including main.js, and you are done. Commented Jan 21, 2014 at 6:30
  • Holy crap you got a lot of answers for this one lol. Well done. Commented Jan 21, 2014 at 6:33

7 Answers 7

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

u dont need to have myVar in the callback's parameter. It would be global. rather myVar will be overwritten with the event object there.
Sorry, so used to building machine learning and avoiding globals :-P
1

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>

3 Comments

I don't think he wanted classes and ids :-(
Eh? I just thought myVar should contain different selectors on different pages.
As much as I agree, I didn't ask the question ;-)
0

You can define myVar before you include main.js

var myVar = "someThing";

--include main.js

Comments

0

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>

Comments

0

Try initializing myVar before you load main.js

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

Comments

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

1 Comment

Not sure he was looking for a specific jQuery ID or Class, but rather a variable.
0

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));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.