How to add a JS JavaScript to a module ?
Add JavaScript as libraries
Like a CSS, You can add a JS as a librarie
Example:
1.1 Add a librarie.
-> Create a file modulename.libraries.yml
-> Add JS file, Exemple:
myjs:
version: 1.x
js:
js/myjs.js: {}
dependencies:
- 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
libraries:
- mybartik/myjs
3. Add libraries from twig templates:
{# In a Twig template we attach the library. #}
{{ attach_library('bartik/messages') }}
NOTE:
If you use jQuery, Your JS file must be like:
(function ($) {
//Jour jQuery codes ...
})(jQuery);
Use Drupal behaviors
Example 2:
//modulename.libraries.yml
myjs:
version: 1.x
js:
js/script.js: {}
dependencies:
- 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(
array(
'#tag' => 'script',
'#value' => \Drupal\Core\Render\Markup::create('alert("Yes")'),
),
'my_scripts'
);
JavaScript API in Drupal 8 : https://www.drupal.org/node/2269515
Comments