In my Drupal 7 installation, I have 2 separate JavaScript files that are loaded by my sub-themes (base and admin sub-theme) - I don't know if this is useful information or not, but:
What if I want to define a JavaScript variable in the first js file that is loaded and use it in the second one? How should I define it?
Basically, the question could be: How to define global JavaScript variables in a Drupal environment?
I am using jQuery.
Thanks in advance!
Edit:
First js file:
var myOwnVar;
(function ($) {
$(document).ready(function() {
myOwnVar = 1;
});
}(jQuery));
Second js file:
(function ($) {
$(document).ready(function() {
console.log(myOwnVar);
});
}(jQuery));
In my Drupal 7 installation, I have 2 separate JavaScript files that are loaded by my sub-themes (base and admin sub-theme) - I don't know if this is useful information or not, but:
What if I want to define a JavaScript variable in the first js file that is loaded and use it in the second one? How should I define it?
Basically, the question could be: How to define global JavaScript variables in a Drupal environment?
I am using jQuery.
Thanks in advance!
Edit:
First js file:
var myOwnVar;
(function ($) {
$(document).ready(function() {
myOwnVar = 1;
});
}(jQuery));
Second js file:
(function ($) {
$(document).ready(function() {
console.log(myOwnVar);
});
}(jQuery));
Share
Improve this question
edited Jan 9, 2013 at 13:01
MrUpsidown
asked Jan 9, 2013 at 11:51
MrUpsidownMrUpsidown
22.5k15 gold badges83 silver badges141 bronze badges
1
- did u find ans to this problem, I am having same issue – Hitesh Commented Nov 14, 2014 at 12:21
1 Answer
Reset to default 6You want to use Drupal.settings.
The values can be globally accessed across the JavaScript functions.
You can pass variables from your PHP to JS...
drupal_add_js(array('YOURMODULE' => array('SOMEVARIABLE' => 'woohoo')), 'setting');
Then access the variable in your JS function...
(function ($) {
Drupal.behaviors.YOURMODULE = {
attach: function (context, settings) {
// You can access the variable by using Drupal.settings.SOMEVARIABLE
alert(Drupal.settings.YOURMODULE.SOMEVARIABLE);
}
};
})(jQuery);
Please refer to http://drupal/node/172169#variablesandarrays
"Variables should not be defined in the global scope; try to define them in a local function scope at all costs. All variables should be declared at the beginning of a function."
Alternatively, the following outside of any closures will work but should be avoided.
var SOMEVARIABLE = SOMEVALUE;
(function ($) {
Drupal.behaviors.YOURMODULE = {