Drupal behaviors

Viewed 43885
  • What are Drupal behaviors at all?
  • What type of service layer it offers to module developers?
  • What type of relation it maps to jQuery.ready?
7 Answers

Drupal has a ‘behaviors’ system to provide a modular and better way for attaching JavaScript functionality to place elements on a page. Drupal Behaviors allows you to override or extend the existing behavior. These Drupal behaviors are event triggered programs that get attached to the page elements to be changed. While behaviours can be attached to specific contents, multiple behaviours are also attached and can be ablazed multiple times for a quick remake.

JavaScript by attaching logic to Drupal.behaviors. Here is an example taken from that page:

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    $('.example', context).click(function () {
      $(this).next('ul').toggle('show');
    });
  }
}

;

Step 1. creating info file like my module name is "mymodule.info.yml".

 name: My Module  
 type: module  
 description: 'for js file.'  
 core: '8.x'  

Step 2. creating .module for use of hook to attached js file to module.

 <?php  
 // use hook for attachment of library to module   
 function mymodule_page_attachments(array &$page) {  
  // using this variable we are creating js file initialization  
   $page['#attached']['library'][] = 'mymodule/mymodule-js';  
   $page['#attached']['drupalSettings']['mymodule'];  
 }  
 ?>  

Step 3. creating mymodule.libraries.yml for attached js file

 mymodule-js:  
  version: 1.x  
  js:  
   js/mymodule.js: {}  
  dependencies:  
   - core/jquery  
   - core/drupalSettings  

Step 4. after creating libraries you have to create js folder then inside the js folder you have to add js/mymodule.js file then you can write code of Drupal behavior.

 Drupal.behaviors.mymodule = {  
  attach: function (context, settings) {  
   // using this code we are just for learning proposed we just add class on site logo 
   you can write code of js below the comment.  
   jQuery('.site-branding__logo' , context).addClass('fancy-pants');  
  }  
 }  

Above four steps you can add js using Drupal behavior let me know this post helpful or not for you to comment on if you have questions about my blog post.

Related