Add JavaScript to a module | Drupal 8

Add JavaScript to a module

Submitted by editor on Mon, 12/07/2015 - 13:05

How to add a JS JavaScript to a module ?

Add JavaScript as libraries

Like a CSS, You can add a JS as a librarie

1.1 Add a librarie.
 -> Create a file modulename.libraries.yml
-> Add JS file, Exemple:
  version: 1.x
      js/myjs.js: {}
    - core/jquery

1.2 Create CSS file and put it in to the module_folder/js/myjs.js
1.3 Attach librarie to the block
In your build() methode, add to the output array,
    $output[]['#attached']['library'][] = 'modulename/myjs';

2. If yoy want to add tl all pages, Add librarie to the .info.yml File
  - mybartik/myjs

3. Add libraries from twig templates:
{# In a Twig template we attach the library. #}
{{ attach_library('bartik/messages') }}

If you use jQuery, Your JS file must be like:

(function ($) {
//Jour jQuery codes ...

Use Drupal behaviors

Example 2:
  version: 1.x
    js/script.js: {}
    - core/drupal
    - core/jquery

NOTE : Dependencies
To use Drupal, you must add - core/drupal
To use $ (jQuery), you must add - core/jquery
To use drupalSettings, you must add - core/drupalSettings

//JavaScript File :  js/script.js
(function ($, Drupal, window, document) {
  Drupal.behaviors.basic = {
    attach: function (context, settings) {
      $(window).load(function () {
        // Execute on page load
      $(window).resize(function () {
        // Execute code when the window is resized.
      $(window).scroll(function () {
        // Execute code when the window scrolls.
      $(document).ready(function () {
        // Execute code once the DOM is ready.

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

Add inline JS to a custom page.

Note : In drupal 7 you can use drupal_add_js, but not in Drupal 8.

To add an inline javascript you can use #attached of drupal render array. Example:

$output['#attached']['html_head'][] = array(
    '#tag' => 'script',
    '#value' => \Drupal\Core\Render\Markup::create('alert("Yes")'),


JavaScript API in Drupal 8 :

Add new comment

Plain text

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