-1

I would like to declare a global variable but on a different page. So all my global variables go on data.js and all the JavaScript functions go on script.js I can do it in JavaScript but how do you do it in jQuery?? When I put my all JavaScript Codes in

$(function() {
    //JavaScript Codes

});

It doesn't work any more.

Here's my code:

http://plnkr.co/edit/u9CLTErGugOZoDTonAl3?p=preview

4
  • What do you mean with "on a different page"? Commented Sep 3, 2014 at 23:27
  • Nothing changes. Normal JavaScript rules apply. (However, do be aware that "onready" is not executed synchronously.) Anyway, what "doesn't work"? The demo code (a version of which should be included inline in the question) appears to run just fine. Commented Sep 3, 2014 at 23:28
  • Just curious, why you wanna do it? Commented Sep 3, 2014 at 23:30
  • Why do you need global variables? Polluting the global namespace is bad practice and unsafe as anyone at any time can overwrite those variables without you knowing. Using name-spacing and/or patterns such as the Module/Revealing Module pattern might help. Also the use of local storage or similar, if that is required, could also be an option. There is many options aside from polluting the global namespace. It would be good to know why you think you need globals and see if the issue can be solved otherwise before creating a file specifically to host them. Commented Sep 3, 2014 at 23:37

2 Answers 2

2

All global javascript variables are attached to the window object. You can explicitly bind them to the window object:

$(function() {
    window.test = "Hello";
});
alert(test);

You could also not use the keyword var and they will be implicitly bound to the window object:

$(function() {
    test2 = "World";
});
alert(test2);

Fiddle: http://jsfiddle.net/6tfr2mh6/

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

2 Comments

That creates them as properties of the global object, which is subtly different to global variables, e.g. global variables are available before any code executes, whereas global properties are only available once the code that creates them executes (which might be never).
Oh, I didn't know that. This answer's incorrect then. I googled it upon your response and a much better answer is here for anyone interested: stackoverflow.com/questions/4862193/javascript-global-variables
1

You can simply use javascript variable and use it in another script using jquery. You do not need to declare variable using JQuery.

In data.js

var myValue = "I'm on top of the world!!";

In script.js

$(function() {

  var myFunction = function() {
    $("#demo").html(myValue);
  }

  myFunction();
});

You can see preview here: http://plnkr.co/edit/A9W1rE39DqSLzChX8Qk9?p=preview

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.