0

I made a custom js script for a little calculator. I want to use this in only 1 node (article or page) so I do not want to load it via tpl files etc because I do not need it sitewide. And also: if every custom script (that I use only in 1 node) has to be loaded sitewide I would get an immense head section after some time. Does anyone have experience with how to do this in a simple and safe way?

Thanks. Frank

3
2

In the template.php you will write this small piece of code:

function MYTHEME_preprocess_node($vars) {
 if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'yournid') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/script/js");
 }
}

Replace foo with values related to your need.

0

code for adding JS to particular path:

if ($_SERVER['REQUEST_URI'] == '/path/to/node') {
  drupal_add_js('somefile.js');
}

to attach js to node:

function my_module_node_view($node, $viewmode, $langcode) {
  $node->content['#attached']['js'][] = array('type' => 'file','data' => drupal_get_path('module', 'my_module') . '/my_script.js',);
}

Thanks!

0

Another option is JS Injector. Though I haven't used this module. This requires no programming as it provides user interface to administrators.

-1

you need to use php filter or need to create tpl file for single node to accomplish this. With php filter or tpl you need to put only this code.

<?php 
  drupal_add_js('jQuery(document).ready(function () {
    jQuery("p").hide();
    jQuery("p").fadeIn("slow");
  });', 'inline');
?>
2
  • PHP filter is highly discouraged.
    – Brady
    Aug 28 '15 at 11:44
  • I understand it creates a potential security risk especially in the hands of end users or people new to Drupal or PHP.
    – vgoradiya
    Aug 28 '15 at 11:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.