jQuery.ready
?JavaScript is used and loaded in special ways within a Drupal site. JavaScript is loaded via asset libraries and Drupal core provides a bunch of different JavaScript libraries that you can load and use in your module or theme. This tutorial provides a brief orientation to some of the JavaScript included in core.
A JavaScript library to select and filter DOM elements to process them only once. The releases and API documentation for this project can be found on npm under @drupal/once.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With