0

I have the following code which works:

<?php
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'job_node_form') {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  }
}
?>

but the following doesn't:

<?php
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'job_node_form') {
    drupal_add_js(drupal_get_path('module','conflict') . '/js/test.js');
  }
}
?>

The code in sites/all/modules/mymodulename/js/test.js is:

If(Drupal.jsEnabled) {
  $(document).ready(function() {
    alert("Hello!");
  });
}

And when I look in the page source when I'm in "job_node_form", I can see the js file loaded.

Edit:

I've found that:

$(document).ready(function()

is causing the issue. I've tried both $ and jQuery.

Is the inline code timed differently to the code in a js file? I'm wondering if the code in the js file runs before all DOM objects are loaded?

  • 1
    Propably jsEnabled not defened yet, moreover if browser unsupports js, whole code will not able to execute. Try this jQuery(document).ready(function($) { alert('123'); }); in your file or try $form['#attached']['js'][] = array('data' => 'path_to_js_file.js', 'type' => 'file'); – Oleg Sherbakov Jul 9 '13 at 20:15
  • Additionally, the script may be loading before jQuery -- what errors do you see in Firebug/Inspector? Try adding the group parameter THEME, or a low weight (see api.drupal.org/api/drupal/includes!common.inc/function/… for options.) – Renee Jul 9 '13 at 20:19
  • Or module named mymodule and you try to load file from "conflict" module, that doesn't exists. :) – Oleg Sherbakov Jul 9 '13 at 20:28
5

With Drupal instead of using $(document).ready, you can/should use Drupal.behaviors. Here is a boilerplate JavaScript wrapper you can use:

(function($, Drupal) {

  // Custom functions and variables can go here

  Drupal.behaviors.moduleName = {
    attach:function() {
      // Put your document's onload code here
    }
  };
}(jQuery, Drupal));

By the way, now that it's all done, to go back to the original topic, I wouldn't/don't use drupal_add_js() at all. Instead, you can do this:

<?php
if($form_id == 'job_node_form') {
  $form['#attached']['js'][] = array(
    'type' => 'file',
    'data' => drupal_get_path('module','conflict') . '/js/test.js',
  );
}
?>

This attaches the file directly to the form, allowing it to be overridden further down the line through the context of the form it belongs to.

-2
function mymodule_submit_add_js($file) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . "/js/name.js");
}
  • Hello. Please avoid code-only answers. – Mołot Feb 6 '14 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy