Drupal behaviors

One of the most important things you need to know when writing JavaScript files in Drupal is the concept of behaviors. But in order to understand that, let's get a bit of context.

When writing JavaScript code using jQuery, it's often standard to wrap our code inside a ready() method statement as follows:

$(document).ready(function () { 
  // Essentially the entirety of your javascript code. 
}); 

This ensures that your code runs only after the entire Document Object Model (DOM) has been loaded by the browser. Moreover, the use of jQuery for this helps a great deal with cross-browser compatibility and also allows us to place this code wherever we want on the page (header or footer).

In Drupal, however, we have a different solution which is better in the context of writing JavaScript that works with Drupal as well (not just with the DOM). That comes in the form of Drupal behaviors. In a nutshell, behaviors are methods we declare that get called when the DOM loads fully, that is, when the document is ready. However, on top of that, they also get called by the Ajax framework when new data is loaded onto the page. Even when using BigPipe and placeholder replacements are streamed.

Any Drupal site has a global Drupal object that is used for many things we won't go into right now. However, the Drupal.behaviours object is where we declare behaviors, and typically any JavaScript code that we want to run should go inside a behavior. So, let's see an example, as it will be much easier to understand.

What we want is to show a little dynamic JavaScript clock next to the Hello World salutation, if the message is not coming from the configuration but is dependent on the time of day. While writing the code for our functionality, we'll talk about Drupal behaviors and how they are used.