How to write a basic Javascript behaviour in Drupal

 A Drupal behavior is a JavaScript object created under Drupal.behaviors object.

(function ($) {
  Drupal.behaviors.MYMODULE = { attach: function (context, settings) {
      // Your Javascript code goes here

    }
  };
}(jQuery));


Our behavior must contain an 'attach' method, and can also optionally contain a 'detach' method. As you can imagine, 'attach' is called when the behavior is activated, while 'detach' is called when it is de-activated. In most cases, you don't have to implement the 'detach' method, unless you have some cleanup to do in JavaScript (which is rare). The two arguments to the behavior are - context and settings.
  1. Context is the DOM object to which the behavior is attached. This could be the form, the form element or often the 'document' object. Typically, you would apply your JavaScript behavior to the 'context' object or its children.
  2. Settings can be special JavaScript object supplied at the time of attachment, but most of the times it is same as Drupal.settings. 
Assume that you have a variable in .module(block_example) file and you want to simply print a JavaScript alert of that variable.

1. Your variable(SOMEVARIABLE) in .module file
=======================
drupal_add_js(array('YOURMODULE' => array('SOMEVARIABLE' => 'woohoo')), 'setting');

2. Write your own JS file
==================
Assume that your JS file name is myjsfile.js. Place the following contents in JS file.

(function ($) {
  Drupal.behaviors.YOURMODULE = {
    attach: function (context, settings) {

      // You can access the variable by using Drupal.settings.SOMEVARIABLE
      alert(Drupal.settings.YOURMODULE.SOMEVARIABLE);
   //alert(Drupal.settings.basePath);
    }
  };
})(jQuery);


3. Include JS file in .module
=====================
drupal_add_js(drupal_get_path('module', 'block_example') .'/myjsfile.js');

 When page is loaded you should see 'woohoo' in alert.


Other JS ToDos:
============
1. If you have a set of JavaScript and/or CSS that could be considered a package, provide it as a library to other modules by implementing hook_library(), and include it it in your own pages either by using #attached['library'] or drupal_add_library(). This is the preferred way to deal with JavaScript and CSS which might be used by other modules.



Comments

  1. To overwrite a JS function it is also possible using Addtohead module. It may required in some production hot fixes. For example following code is added in addtohead / page bottom.

    Drupal.ajax.prototype.commands.viewsScrollTop = function (ajax, response, status) {
    // Your debugging code here
    };

    ReplyDelete

Post a Comment

Popular posts from this blog

Programatically create layout builder section in Drupal

Code quality analysis of Drupal. Can I use Sonar?

Set up Drupal7 to Drupal8 migration in simple steps (using Drush)