How do I write custom JavaScript in my Drupal theme?

February 12, 2024
default author headshot Ashraf Abed
Share this post:

There are many instances where people need to write custom JavaScript on a Drupal website. In fact, a former graduate of our Drupal bootcamp sent me, the lead instructor, a message in our alumni slack channel asking for tips on how to create a custom Hamburger menu using JavaScript (with the help of jQuery) in Drupal.

After responding to their question, I decided to share it as a blog post. The below content is copy and pasted from our Drupal Training courses alumni chatroom.

Before we got to the main question, we had to address the prerequisite:

How do you add custom JavaScript to Drupal?

At a high-level, the simplest way to add custom JavaScript to Drupal is:

  • Create a .js file in your custom theme
  • Reference the .js file in a Drupal library (within your theme's themename.libraries.yml file)
  • Ensure the library is being loaded within your theme's file
  • Write your JavaScript code within the .js file, wrapping it in an "attach" function of a custom Drupal Behavior

If that's enough detail for you - great! Get started! If you'd like more detail, read on.

Example of custom JavaScript in Drupal

In most cases, adding JS to a Drupal theme consists of:

  1. Creating a javascript file in your theme. If your theme's folder is "mytheme", you could put your js file anywhere inside of it, such as: (mytheme/js/myfile.js)
  2. Updating the existing libraries.yml file in your theme: mytheme/mytheme.libraries.yml:

In the libraries yml file, you should see a line that says css: followed by line(s) with paths to CSS files. You'll do the same thing for JS. Add a line that says js: , and on the next line write the path to your js file followed by : {}. For example, you could write js: on one line then js/myfile.js: {} on the very next line. Make sure your spacing and formatting is the same as how the css lines are spaced

At the very end of the libraries yml file, add:

  - core/jquery
  - core/drupal

In your js file (mytheme/js/myfile.js), create a "Drupal behavior" as follows:

(function ($, Drupal) {
 'use strict';

 Drupal.behaviors.myCustomJavaScript = {
  attach: function attach() {
    alert("Your javascript code is running. Replace this line");
})(jQuery, Drupal);

How to test JavaScript in Drupal

You may have noticed the code sample above includes an "alert". This alert provides a simple popup message, and an easy way to confirm that your JavaScript code is actually running.

Clear your site's cache and refresh the homepage. If the code is working, you should see the pop up message.

If it's not working, try disabling "JavaScript aggregation" under Configuration > development > performance. Then clear the cache again and refresh the homepage

If you still don't see the pop up, there may be a typo or bug somewhere.

If the pop up works, you can move on to write your custom code.

  1. Substitute the name "myCustomJavaScript" with whatever name you like (no spaces or dashes)
  2. Substitute the text alert("Your javascript code is running. Replace this line"); with whatever javascript code you want to run

Become a skilled Web Developer with Tailored, Hands-On Training: Debug Academy

The above text is an excerpt of a short conversation in our alumni chat. There's more to the picture and we would love to share it with you. If you’re serious about learning the skills required for web developer and want to speed up the process, you can trust Debug Academy. We’ll teach you the web developer required skills in a structured manner that helps you hit the ground running fast - and most importantly, with confidence!

Our approach blends structured learning with hands-on, real-world projects, guided by experienced professionals. Whether you're a beginner or looking to upgrade your skills, our comprehensive curriculum covers everything from fundamental coding principles to advanced web technologies. 

With personalized mentorship, collaborative projects, and a supportive community, Debug Academy is committed to transforming you into a proficient, job-ready web developer. 

Experience the most efficient and effective path to a successful career in web development with Debug Academy. We have free Drupal training to help you get a sense of what’s possible in this field along with a more advanced curriculum. Learn about our Drupal certification trainingDrupal migration services, and all the other Drupal courses we have to offer today!

The above text was copy-pasted from our alumni chatroom. The alumni chat is available to all graduates of our long-form Drupal training courses.

Ready To Launch Your Career?

Take the first step to launching the career you've always wanted. Explore Debug Academy classes today!

Explore Classes Contact Us