On the SO-chat, I was advised to ask the following question here:
I would like to load some Javascript globally on my complete website, via a Drupal theme's Javascript; insead of having to re-insert the Javascript-code each article over and over again.
For example, I have managed this with the following code (imagine it wrapped in <script type="text/javascript">
...</script>
, when inserted locally):
(which worked fine both locally when inserted per page, and also when loaded in to the Drupal theme's javascript globally as such):
(function ($) {
$(document).ready(function () {
$
$(".toggler").click(function () {
$(this).next().slideToggle("slow");
}).next().hide();
$("a[href^=#]").click(function () {
var id = $(this).attr('href');
$(id).parents('.toggled').fadeIn("fast");
});
});
})(jQuery)
However, for 2 other pieces of Javascript, I can't get things to work when loading them globally. However, they work great when inserted locally in to each consecutive article, as such (I'll mention just 1 smaller code, for reference):
(imagine it wrapped in <script type="text/javascript">
...</script>
again, when inserted locally):
(function($) {
$(document).ready(function() {
function getKey(element) {
return element.href;
}
function sameGroupAs(element) {
var key = getKey(element);
return function() {
return getKey(this) === key;
}
}
$(document).on("mouseenter", "a", function() {
$("a").filter(sameGroupAs(this)).addClass(
"active");
}).on("mouseleave", "a", function() {
$("a").filter(sameGroupAs(this)).removeClass(
"active");
});
});
})(jQuery)
Just for reference: if you would be interested how I added the Javascript to a Drupal's theme.
The solution was simply to put every single "script" in a seperate .js
-file. If they were put into one .js
-file, they would simply all become dysfunctional.
Anyone knows whether this is a Drupal-specific strategy, or whether this is general to Javascript and known to everyone in "the field"?