Drupal Behaviors - JavaScript and jQuery | Drupal 8

Drupal Behaviors - JavaScript and jQuery

Submitted by editor on Wed, 06/08/2016 - 15:45
Question

What is drupal behaviors ?
How to use drupal behaviors on drupal 7 ?
How to use drupal behaviors on drupal 8 ?

What is drupal behaviors ?

Drupal behaviors allow to execute javascpts in particular context and / or pass data from drupal to client side java script.

Example on Drupal 8.

Add settings from drupal

/**
 * Implements hook_js_settings_alter().
 *
 * @inheritdoc
 */
function myModule_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  $settings['myModule']['text'] = "The text";
}

Include script, drupal and jQuery

Example : File mymodule.libraries.yml
mymodule:
  js:
    lib/myscript.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Get settings from drupal Settings.

Example : File : lib/myscript.js
(function ($, Drupal, drupalSettings) {
    //Get settings from Drupal
    var text = drupalSettings.myModule.text;
    Drupal.myModule.show = function () {
        alert(text);
    };
    // Show Message on ready.
    $(document).ready(function () {
        Drupal.myModule.show();
    });
})(jQuery, Drupal, drupalSettings);

 

Drupal behaviors On drupal 7 (Example)

Add the acript and settings using drupal_add_js()

Example:
// Add script.
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/myscript.js', 'file');
// Add settings.
drupal_add_js(array('mytheme' => ['text' => "The text"]), 'setting');

Get setting (Read from java script)

Example : File : /js/myscript.js
(function ($, Drupal) {
  Drupal.behaviors.parrotRootRedirect = {
    attach: function (context, settings) {
      var text = settings.mytheme.text;
        alert(text);
    }
  };
})(jQuery, Drupal);

Add new comment