Search code examples
javascriptdrupaldrupal-8pure-js

Drupal 8 Drupal.behaviors without jquery


Is there a way to add drupal behaviors to a theme without invoking jquery in Drupal 8?

This is what the tutorial show:

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $('input.myCustomBehavior', context).once('myCustomBehavior').each(function () {
        // Apply the myCustomBehaviour effect to the elements only once.
      });
    }
  };
})(jQuery, Drupal);

But i want to use pure js without invoking jquery, something like this:

(function (Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      context.querySelector('input.myCustomBehavior').classList.add('processed');
    }
  };
})(Drupal);

I understand that modules may invoke jquery on their own but i still would like to remove it from my scripts if possible and still have it run after ajax events.

Thanks


Solution

  • Have you tried it?

    I also did not know this, so went investigating.

    It seems that Drupal no longer relys on jQuery's document.ready to fire behaviors.
    As seen in this change record.

    This leads me to believe that the second code block that you posted should work (with Drupal 8.x).