4

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

wolfhowling
  • 83
  • 1
  • 7

1 Answers1

1

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).

2pha
  • 9,798
  • 2
  • 29
  • 43
  • I have tried multiple versions of what i wrote without success, what you found looks promising but i cant find a way to make it work yet, `domready(function () { });` works just the same as `(function () {});` but it wont work after ajax or with bigpipe i also found `domready(function () { Drupal.attachBehaviors(document, drupalSettings);}); ` but i cant find how to implemented properly. – wolfhowling Jul 19 '18 at 15:46
  • 2
    In the end your answer lead me to figure it out. It turns out that bigpipe requires jquery therefor it was going counter to what i was doing with js and it caused it to failed when i disabled bigpipe the second code block worked just fined with ajax. Thanks – wolfhowling Jul 19 '18 at 16:58
  • 3
    Bigpipe does indeed rely on jQuery, as can be seen in [the source](https://cgit.drupalcode.org/drupal/tree/core/modules/big_pipe/js/big_pipe.js?h=8.5.x). This makes me sad :( – 2pha Jul 19 '18 at 23:35
  • From Drupal 9.3 bigpipe do NOT depend on jQuery anymore. See https://www.drupal.org/project/drupal/issues/3204273 – gagarine Aug 16 '22 at 09:27