0

Migrated website from 7 to 10, but the jQuery scripts do not work anymore.

Code:

(function ($, Drupal, window, document, undefined) {
  Drupal.behaviors.myLinebreak = {
    attach: function (context, settings) {

        var eles = document.querySelectorAll('.title');    
        [].slice.call(eles).forEach(function(ele) {
          ele.innerHTML = ele.innerHTML.replace(/,/g, ',<br/>')
        });    
  }
};

})(jQuery, Drupal, this, this.document);

HTML:

<span class="title">Break this line, after comma</span>

What it does is that it injects <br> after the comma.

It works fine on Drupal 7:

<span class="title">Break this line,<br>after comma</span>

But on Drupal 10 it adds the <br> five times:

<span class="title">Break this line,<br>
<br>
<br>
<br>
<br>
after comma</span>

Why does it repeat on Drupal 10? It's same exact structure like Drupal 7. (there's more than one .title element on the page)

Using js_injector on Drupal 7 and assets_injector on Drupal 10

1

1 Answer 1

2

This code executes its attached code on document instead of on context. With document, the code will re-run on the entire document if Ajax adds anything to the DOM, whereas with context the code will run initially on the document, then on added elements as they appear.

So, there is probably some Ajax happening and this code repeatedly replaces the comma with ,<br>. In short, replace document.querySelectorAll with context.querySelectorAll.

But context alone might not be enough, as sometimes DOM elements may be passed in again. If that is the case you should also use once.

5
  • 1
    Using once is another option
    – Clive
    Commented Nov 19 at 0:43
  • Hi, this works better, but still produces 2 <br><br> instead of 5? I am very confused. Commented Nov 19 at 13:22
  • Which works better? Indeed, the answer is just above. In addition to context you should use once().
    – mona lisa
    Commented Nov 19 at 13:24
  • Where do I put once() exactly I'm not very good with jQuery, thanks. Commented Nov 19 at 14:55
  • 1
    I don't think jQuery is involved here. Your code injects three things it does not use: jQuery, this (the document), and this.document. once is not a jQuery library. The change record from back in Drupal 9 explains: drupal.org/node/3158256.
    – mona lisa
    Commented Nov 19 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.