Module 1.2 – JavaScript and jQuery in Drupal

This module validates whether a Drupal developer understands how JavaScript is integrated into Drupal without breaking performance, accessibility, or maintainability.

Acquia is not testing advanced JavaScript frameworks. It is testing whether you understand Drupal’s JavaScript architecture, especially behaviors, libraries, and proper attachment patterns.


1. JavaScript in Drupal is framework-managed

Drupal does not expect developers to write free-form JavaScript attached directly to the DOM.

JavaScript execution is controlled by Drupal core to support:

  • Ajax responses
  • Partial page refreshes
  • Progressive rendering
  • Accessibility

Any JavaScript that ignores this system will fail in real projects and is usually incorrect in exam questions.


2. Drupal behaviors are mandatory

Drupal uses behaviors to ensure JavaScript runs:

  • On initial page load
  • After Ajax requests
  • When new markup is injected

Core concept

A behavior is an object with an attach function. Drupal automatically calls it when needed.

Example behavior

(function (Drupal, once) {
  Drupal.behaviors.exampleBehavior = {
    attach: function (context) {
      once('example-behavior', '.example-selector', context).forEach(function (element) {
        element.addEventListener('click', function () {
          console.log('Clicked');
        });
      });
    }
  };
})(Drupal, once);

Key rules:

  • Never rely on document ready
  • Always use context
  • Always use once to prevent duplicate bindings

3. Real-world scenario – Ajax-rendered content

Scenario: A form updates part of the page using Ajax and injects new markup.

Incorrect approach:

  • Using jQuery document ready

Correct approach:

  • Using Drupal behaviors

Why:

  • Document ready runs only once
  • Behaviors re-run automatically on Ajax updates

Acquia exam questions frequently test this exact scenario.


4. The once API

The once API ensures that JavaScript is applied only once per element, even if behaviors are reattached.

Without once:

  • Event handlers are duplicated
  • Performance issues occur
  • Bugs appear after Ajax calls

Using once is considered a best practice and is expected in exam answers.


5. JavaScript libraries in Drupal

JavaScript must be defined and managed using libraries.

Example libraries.yml

example-behavior:
  js:
    js/example-behavior.js: {}
  dependencies:
    - core/drupal
    - core/once

Inline JavaScript and direct script tags are discouraged.


6. Attaching JavaScript libraries

Libraries can be attached in multiple Drupal-approved ways.

Global attachment

Attach in theme info.yml for site-wide behavior.

Contextual attachment

Attach via render arrays or preprocess functions for specific pages, blocks, or components.

Twig attachment

{{ attach_library('mytheme/example-behavior') }}

Best practice is to attach JavaScript only where needed.


7. jQuery usage in modern Drupal

jQuery is still available but is no longer the default approach.

Preferred practices:

  • Use vanilla JavaScript where possible
  • Use jQuery only when required by existing APIs
  • Declare jQuery as a dependency explicitly

Example dependency:

- core/jquery

Exam answers should not assume jQuery is globally available.


8. Separation of concerns with JavaScript

JavaScript responsibilities:

  • Behavior
  • Interaction
  • Progressive enhancement

JavaScript should not:

  • Generate markup
  • Contain business logic
  • Replace server-side validation

Acquia exam questions often test whether logic is incorrectly pushed into JavaScript.


9. Accessibility considerations

JavaScript must not break:

  • Keyboard navigation
  • Focus management
  • Screen reader flow

Examples:

  • Use button elements, not clickable divs
  • Preserve focus after Ajax updates

Accessibility violations are considered incorrect in exam scenarios.


10. Performance considerations

Poor JavaScript practices cause performance issues.

Common mistakes:

  • Global libraries loaded everywhere
  • Duplicate event bindings
  • Heavy DOM queries

Correct approach:

  • Attach libraries conditionally
  • Use once
  • Scope selectors to context

11. Exam traps to watch for

  • Using document ready instead of behaviors
  • Inline JavaScript in Twig
  • Forgetting once
  • Assuming jQuery is always available
  • Attaching JavaScript globally without need

These options are usually incorrect in multiple choice questions.


Key exam takeaways

  • Drupal behaviors ensure JavaScript works with Ajax and dynamic content
  • Libraries control how JavaScript is loaded
  • once prevents duplicate execution
  • JavaScript should enhance behavior, not control logic

Practice check

  • How does Drupal rerun JavaScript after Ajax: behaviors
  • How do you prevent duplicate handlers: once
  • Where should JavaScript be defined: libraries
  • When should JavaScript be attached globally: only when truly site-wide