Drupal behaviors

JqueryDrupalDrupal 6

Jquery Problem Overview


  • 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?

Jquery Solutions


Solution 1 - Jquery

Long version: Drupal.behaviors is not simply a replacement for jQuery.ready since the latter only runs once (when DOM is ready for manipulation): behaviors can be fired multiple times during page execution and can be run whenever new DOM elements are inserted into the document.

Also, modules could override or extend an existing behavior (e.g. if one module has a behavior of adding a bounce effect on all links, a second module could replace the behavior by a different bounce effect).

Short version: it's more modular, though the documentation could be improved.


Also, starting in Drupal 7, settings defined using drupal_add_js (PHP) or in Drupal.settings.modulename (Javascript) are directly passed as second parameter (the first one being the context) to the behavior.

For example:

Drupal.behaviors.changeLinks = function(context, settings){
	if (!settings) settings = Drupal.settings.changeLinks;
	$("a", context).hover(function() {
		$(this).css('color', settings.color);
	});
};

And if one of your script (or another) creates new nodes, it could still have the behaviors applied to the new nodes without having to know what other modules are iinstalled:

var newNodes = $('<a href="#">Hello</a> <a href="#">World</a>').appendTo('#someDiv');

Drupal.attachBehaviors(newNodes);

Solution 2 - Jquery

Duplicated Functionality

Note that the Drupal.behaviors architecture duplicates functionality already in jQuery.

Also, as of this writing, there does not appear to be any documentation or case studies for Drupal.behaviors outside of Drupal itself; and the documentation within Drupal (as stated above) could benefit considerably from improvements. As of this writing, it appears that the primary detailed documentation is restricted-access for-fee only.

This means you may notice performance degredation, anomalies, and unexpected results not consistent with standard jQuery that are endemic to the Drupal.behaviors ecosystem.

Native jQuery Functionality

In contrast to Drupal.behaviors, the built-in functionality of the standard jQuery API is extensively documented including in-line demonstrations and examples. Moreover, there are numerous live examples freely available on sites such as jsfiddle.

The links in the see also section enumerate the jQuery api calls relevant to handling new DOM elements inserted into the document.

See also

Solution 3 - Jquery

Along with answers mentioned above on of the key things is you can pass data from php to javascript which is as follows

Passing values from PHP to Javascript with "Drupal.settings"

You can easily make variables from PHP available to Javascript on the front end with Drupal.settings using drupal_add_js() function

<?php
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
?>

or

<?php
$element['#attached']['js'][] = array(
  'type' => 'setting',
  'data' => array('myModule' => array('key' => 'value')),
);
?>

This will be available in Javascript as:

  if (Drupal.settings.myModule.key === 'value') {
    alert('Got it!');
  }

Solution 4 - Jquery

Looking for a similar answer and arrived here, still without clues. Finally found a little more explanation (and examples) from an article here: https://benmarshall.me/drupal-behaviors/

I am not the original author, so I can only quote some texts:

> What are Drupal Behaviors? > > In short, Drupal.behaviors is a more modular and better way to > implement jQuery.ready. Unlike jQuery.ready which only runs once when > the DOM is ready for manipulation, Drupal.behaviors can be ran > multiple times during page execution. Even better, they can be ran > whenever new DOM elements are inserted into the document (i.e. AJAX > driven content). > > Drupal.behaviors can also override or even extend an existing > behavior. So for instance, if a module behavior adds a bounce effect > on all links, another module could replace that behavior with a > different bounce effect. > > Another added bonus of Drupal.behaviors (starting in Drupal 7), is the > ability to use the drupal_add_js (PHP) or Drupal.settings.modulename > (JS) and pass settings as a second parameter (the first being the > context) to the behavior.

Solution 5 - Jquery

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');
    });
  }
}

;

Solution 6 - Jquery

Drupal behaviors are used if your JavaScript needs to be executed on page load and after an AJAX request (some new elements added in your document/html).

Drupal.behaviors.yourmodulename = {
  attach: function (context, settings) {
     // Code to be run on page load, and
    // on ajax load added here
  }
};

yourmodulename: This is your namespace and should be unique. For example, this is typically the name of your module, but it isn't mandatory.

context: This is actually really really cool, on page load the context will contain the entire document and after an AJAX request will have all the newly loaded elements. This way you can treat content that is loaded in via AJAX differently than others.

settings: This contains information passed on to JavaScript via PHP, it is similar to accessing it via Drupal.settings.

Solution 7 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShoaib NawazView Question on Stackoverflow
Solution 1 - JquerywildpeaksView Answer on Stackoverflow
Solution 2 - JquerydreftymacView Answer on Stackoverflow
Solution 3 - JquerySameerView Answer on Stackoverflow
Solution 4 - Jqueryth.sigitView Answer on Stackoverflow
Solution 5 - JqueryPappu Kumar SinghView Answer on Stackoverflow
Solution 6 - JquerykhurramiView Answer on Stackoverflow
Solution 7 - JqueryomrmankarView Answer on Stackoverflow