Sharing JS variables in multiple <script> blocks Sharing JS variables in multiple <script> blocks codeigniter codeigniter

Sharing JS variables in multiple <script> blocks


It's really important to learn to namespace your variables in JavaScript. Scope matters, and it matters a lot. Right now because you're using the "var" keyword, your stuff will be in the local scope.

Some of the other answers here say that you should move them into the global scope. That works, unless something else overwrites them unintentionally. I highly disagree with this approach, globally scoped variables are bad practice in JavaScript.

Namespacing works like this:

var foo = foo || {} //Use existing foo or create an empty object.foo.bar = foo.bar || {}foo.bar.baz = foo.bar.baz || {}

etc. etc.

This may seem like a lot more work, but it also PROTECTS YOUR VARIABLES.

You can also add a simple namespacing function that safely namespaces everything against the window object. (I cribbed this from somewhere ages ago, and I think I modified it a little but maybe didn't).

Put this at the top of your app and you can namespace stuff with $.namespace("myapp.mydata") and then say myapp.mydata.currentYear = ...

$.namespace = function() {    var a=arguments, o=null, i, j, d;    for (i=0; i<a.length; i=i+1) {        d=a[i].split(".");        o=window;        for (j=0; j<d.length; j=j+1) {            o[d[j]]=o[d[j]] || {};            o=o[d[j]];        }    }    return o;};

Also, if you're new, or want to get hardcore, I recommend reading JavaScript the Good Parts by Crockford.


Declare the variables as global. Just move them outside of the document ready function.

var current_month = <?= $init['current_month']; ?>;var current_year = <?= $init['current_year'] ?>;$(document).ready(function() {....});

current_month and current_year can now be accessed from any script block.


If you declare your variables outside of any function block, they will be global variables, available to any script on the page.

var current_month;var current_year;$(document).ready(function () {    // init    current_month = <?= $init['current_month']; ?>;    current_year = <?= $init['current_year'] ?>;    ...etc...});