Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Drupal Behaviors - JavaScript and jQuery

By editor , 8 June, 2016
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);

Tags

  • Drupal 8
  • Code
  • JavaScript
  • jQuery
Add JavaScript to a module
Run a JavaScript for selected pages (using body class)

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer