-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

user2864740
  • 60,010
  • 15
  • 145
  • 220
user1736786
  • 139
  • 1
  • 4
  • 11
  • What do you mean with _"on a different page"_? – Etheryte Sep 03 '14 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. – user2864740 Sep 03 '14 at 23:28
  • Just curious, why you wanna do it? – bribeiro Sep 03 '14 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. – Nope Sep 03 '14 at 23:37

2 Answers2

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/

Stryner
  • 7,288
  • 3
  • 18
  • 18
  • 2
    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). – RobG Sep 03 '14 at 23:33
  • 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: http://stackoverflow.com/questions/4862193/javascript-global-variables – Stryner Sep 03 '14 at 23:35
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

masum7
  • 822
  • 6
  • 17