Multiple back-to-top links generated on Drupal 9.5+ [patch availabe]

Created on 23 August 2023, over 1 year ago
Updated 19 September 2023, about 1 year ago

Problem/Motivation

After an update from Drupal core 9.4 to 9.5, toc_js generates multiple back-to-top links as it seems the JS gets run several times.

Steps to reproduce

Add toc_js to a content type. Add content with a few h2, h3 elements. Enable "show back to top" links. Add a ToC. See multiple back-to-top links.

Proposed resolution

Prevent toc_js.js from running multiple times. This patch fixes it for me:

--- web/modules/contrib/toc_js/js/toc_js.js	2019-08-28 10:33:56.197662073 +0200
+++ web/modules/contrib/toc_js/js/toc_js.js	2023-08-23 10:34:11.426728074 +0200
@@ -3,7 +3,7 @@
  * Toc_js.
  */

-(function ($) {
+(function ($, Drupal, once) {
   'use strict';

   Drupal.behaviors.toc_js = {
@@ -11,7 +11,7 @@

       var verboseIdCache = {};

-      $('.toc-js', context).each(function () {
+      $(context).find(".toc-js").once("tocjs").each(function() {
         var nav = $(this).find('nav');
         var options = {
           listType: $(this).data('list-type') == 'ol' ? '<ol/>' : '<ul/>',
@@ -144,4 +144,4 @@
     }
   };

-}(jQuery));
+}(jQuery, Drupal, once));
--- web/modules/contrib/toc_js/toc_js.libraries.yml	2023-08-23 15:12:48.332690469 +0000
+++ web/modules/contrib/toc_js/toc_js.libraries.yml	2023-08-23 15:12:21.794269704 +0000
@@ -7,6 +7,7 @@
   dependencies:
     - core/jquery
     - core/drupal
+    - core/once
     - toc_js/tocjs

 tocjs:

It might be possible to just use once("tocjs",".toc-js",context).forEach() but I am not a JS dev, I could not get this to work.

🐛 Bug report
Status

Closed: duplicate

Version

2.1

Component

Code

Created by

🇦🇹Austria tgoeg

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024