In Drupal, you can add your Javascript to module or theme. If the javascript is related to the module logic and independent of the theme, we should add the .js file in the module. Moreover, Drupal already includes the JQuery library. So we can use the JQuery functions in the .js file.
Let’s recall the custom module we have created in previously.
Drupal – Create a Block
i want to show an Javascript alert box whenever the block is shown. Let’s create a custom.js in <drupal_root>/sites/all/custom.
jQuery(document).ready(function() {
alert("Hello World");
});
Next, we have to add the .js file when loading the block. Edit the custom.module.
<?php
/**
* Implementation of hook_block().
*/
function custom_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
//Define the block
case 'list':
$blocks[0]['info'] = t('Block Info');
$blocks[0]['cache'] = BLOCK_NO_CACHE;
return $blocks;
case 'configure':
//TODO: block configurable parameters
$form = array();
return $form;
case 'save':
//TODO: save new configuration
return;
//Display the block
case 'view':
// Add the Javascript reference when showing the view
drupal_add_js(drupal_get_path('module', 'custom') .'/custom.js');
$block['subject'] = t('Block Subject');
$block['content'] = 'Block Content';
return $block;
}
}
There should be an alert box whenever the block appears.
Done =)

One thought on “Drupal – Add Javascript in Module”