This is how you add Drupal 8 JavaScript and CSS to a certain page in your custom theme instead of the methods we are used to in Drupal 7 drupal_add_js
and drupal_add_css
.
Drupal 8 add javascript to a page
In the following example i will show you how to add jquery-selectall a jQuery plugin witten by me for selecting check-boxes and a custom javascript file jquery-selectall-instance.js
to your drupal 8 website.
Once you downloaded the plugin you need and/or created your custom javascript place the files in your theme. I will place the files in
MYTHEME/vendor/jquery-selectall/jquery-selectall.min.js
MYTHEME/js/jquery-selectall-instance.js
Now to add the javascript to the theme in 2 steps.
- Define it as a custom library in your
MYTHEME.libraries.yml
file like sojquery-selectall: js: vendor/jquery-selectall/jquery-selectall.min.js: {} js/jquery-selectall-instance.js: {}
OPTIONAL: You could technically add CSS as well if you would create a css: tag at the same level where js: is like so
jquery-selectall: js: vendor/jquery-selectall/jquery-selectall.min.js: {} js/jquery-selectall-instance.js: {} css: theme: css/jquery-selectall.css: {}
- Now to attach the library to a certain page. In your
MYTHEME.theme
file create a custom logic in thepreprocess_page
and attach the library like so:
function MYTHEME_preprocess_page(&$vars){ // get current path $current_path = Drupal::request()->getRequestUri(); // check for a path if (!empty($current_path) && (substr( $current_path, 0, 6 ) === "/user/")) { // attach our library $vars['#attached']['library'][] = 'pbow/jquery-selectall'; } }
I hope you found this helpful, if you want to know more on defining libraries in drupal 8 visit https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
Like the page is you found this post useful! Cheers!