You have to understand Drupal Behaviors

You have to understand Drupal Behaviors

As a Drupaler, you may see a strange thing. Your Javascript doesn’t affect Drupal Ajax’ data when it’s triggered. This strange thing makes a lot of people confuse it. Drupal is very powerful CMS. Doesn’t it provide a solution to fix it? Yes, it does. Drupal provide many Javascript API. The one of API is called Behaviors. Later on, I’ll tell you about How to use Drupal Behaviors.

Why Javascript can’t do anything on Ajax Data? Here has a post talking about it.

Drupal Behaviors

what does it provide?

As you see below the list of features, Drupal Behaviors which gives you features is created by Drupal Javascript API.
1.It provides a feature which back-end data are sent to front-end. It makes front-end more customized and flexible.

Floating block and Sticky Navigation are also use it to send back-end data to front-end.

2.After Drupal Ajax is called, it can also be changed Drupal Ajax’ data.

views and views load more are also using Drupal Ajax. When Ajax is triggered, their Javascript files which are contained in Behaviors are also executing.

How to use it?

You may think Drupal Behaviors are hard to use it but don’t worry about it. It’s very simple to use it. You just follow below code and paste them into your JS file. It’s done.

Drupal.behaviors.custom_name = {
  attach: function (context, settings) {
    // Write your code here.
  }
};
  1. custom_name: It’s a variable that can be called by yourself.
  2. context: On the first time, the page is loaded completely. This variable will be a Javascript document object. When Ajax is executed, it’ll be changed. Unless you understand it, you have to try to use console.log to see what it is doing.
  3. settings: It includes back-end data.

Unless you know how to include JS files to your project, you can see this post. It’ll help you.

When to use it?

While Ajax is acting on the page, you have to use it.

Conclusion

Drupal Behaviors can let your Javascript code are flexible and recycled. In the same time, it also solves dynamic element problems. It’s a powerful API. I love it. If you have any questions, you can comment below. Later, I’ll reply you.