Today we learning how to add js using Drupal standard code it means Drupal Behaviors let begin how to add js in Drupal 8 module.
Step 1. creating info file like my module name is "mymodule.info.yml".
Step 1. creating info file like my module name is "mymodule.info.yml".
name: My Module
type: module
description: 'for js file.'
core: '8.x'
Step 2. creating .module for use of hook to attached js file to module.
<?php
// use hook for attachment of library to module
function mymodule_page_attachments(array &$page) {
// using this variable we are creating js file initialization
$page['#attached']['library'][] = 'mymodule/mymodule-js';
$page['#attached']['drupalSettings']['mymodule'];
}
?>
Step 3. creating mymodule.libraries.yml for attached js file
mymodule-js:
version: 1.x
js:
js/mymodule.js: {}
dependencies:
- core/jquery
- core/drupalSettings
Step 4. after creating libraries you have to create js folder then inside the js folder you have to add js/mymodule.js file then you can write code of Drupal behavior.
Drupal.behaviors.mymodule = {
attach: function (context, settings) {
// using this code we are just for learning proposed we just add class on site logo
you can write code of js below the comment.
jQuery('.site-branding__logo' , context).addClass('fancy-pants');
}
}
Above four steps you can add js using Drupal behavior let me know this post helpful or not for you comment on if you have question about my blog post.
No comments:
Post a Comment