-1

I just want to trigger a custom javascript function when the site is loaded I have done this with Drupal.behaviors.custom, but it somehow behaviors triggers twice and I see two identical tables. The problem is that I am a beginner and dont know how implement the once() function in my case

custom.js:

Drupal.behaviors.startTable = {
        attach: function () {

            var data = function () {
                return Handsontable.helper.createSpreadsheetData(100, 10);
            };

            var container = document.getElementById('example');

            var hot = new Handsontable(container, {
                data: data(),
                minSpareCols: 1,
                minSpareRows: 1,
                rowHeaders: true,
                colHeaders: true,
                contextMenu: true
            });


        }
    }

Best solution for me would be If I can trigger a Drupal.AjaxCommands.prototype.custom Command and trigger it with the template

Here is the call for the template:

public function handsontable()
{
   return [
      '#theme' => 'mytheme',
      '#attached' => ['library' => ['ajax_example/handsontable']],
         ];
}

Iam also able to call the custom js with a CommandInterface but it only works if there is a callback with a Link or button or from.

I am pretty sure that there is a really easy way, but could not find any solution.

twig template:

<h2>Handsontable Basic Example (100x10)</h2>
<p>
    Head to <a href="https://handsontable.com" target="_blank">handsontable.com</a> to learn more about Handsontable.
</p>

<div id="example"></div>

Maybe it is possible to call the custom js with the twig template?

1

Some thing like this.

(function ($, Drupal, once) {
  'use strict';
  Drupal.behaviors.startTable = {
    attach: function () {
      var container = $('#example');
      $(window).once().on('load', function () {
        var data = function () {
          return Handsontable.helper.createSpreadsheetData(100, 10);
        };
        var hot = new Handsontable(container, {
          data: data(),
          minSpareCols: 1,
          minSpareRows: 1,
          rowHeaders: true,
          colHeaders: true,
          contextMenu: true
        });
      });
    }
  }
})(jQuery, Drupal);

your library then needs: dependencies: - core/jquery - core/drupal

  • that worked thanks a lot. The only problem was, I got serveral errors using $('#example'); Had to change it to document.getElementById('example'); Is this because of 'use strict' ? – verklixt Jan 29 '18 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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