JavaScript Events on Drupal 8. | Drupal 8

JavaScript Events on Drupal 8.

Submitted by editor on Tue, 02/13/2018 - 10:28
Question

How to use JS event such as onclick, onload, onmouseover, onkeypress .... with Drupal behaviors ?

Note : On drupal the best practice is use drupal behaviors but not JS or Jquery codes such as:
<button onclick='myFunction()'>Click</button>

Example : Add event on click ( like onClick='Click01' )

(function ($, Drupal, window, document) {
    Drupal.behaviors.Click01 = {
        attach: function (context, settings) {
            $('#my-button-01').click(function () {
                console.log(this.id);
            });
        }
    };
}(jQuery, Drupal, this, this.document));

See the tutorial : Add JavaScript to a module.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.