logo

Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

GLightbox is a pure javascript lightbox (Colorbox alternative without jQuery)❗

It can display images, iframes, inline content and videos with optional autoplay for YouTube, Vimeo and even self-hosted videos.

Demo GLightbox Download GLightbox

Scroll

Drupal: Replace Colorbox with GLightbox

16/04/2026, by Ivan

1 Introduction

Lightbox plugins have been a staple of Drupal-powered websites for over a decade. They allow editors to display images, videos, and other media in an overlay without navigating away from the current page β€” a pattern visitors expect on modern, media-rich sites.

Colorbox has historically been the go-to solution in the Drupal ecosystem. The colorbox contributed module pairs tightly with Drupal's image field formatters, has a mature API, and enjoys broad community familiarity. However, as the web has evolved, Colorbox shows its age: it depends on jQuery, ships a heavier payload, and lags behind contemporary accessibility expectations.

Enter GLightbox β€” a pure vanilla-JavaScript lightbox library (zero dependencies) with a polished UI, robust accessibility support, and a lightweight footprint. Its corresponding Drupal module integrates cleanly with the same image fields and media entities that Colorbox once handled.

This article walks you through the full migration: from auditing your current Colorbox setup to installing GLightbox, re-mapping field formatters, removing the old module safely, and fine-tuning the new experience for your theme.

πŸ“‹ Scope This guide targets Drupal 9, 10, and 11. Code examples assume a Composer-managed site. Adjust paths and commands for non-Composer setups as needed.

2 Colorbox vs GLightbox: Why Migrate?

2.1 Limitations of Colorbox

Colorbox was created in a different era of the web. Its architecture reflects assumptions that no longer hold in modern Drupal development:

  • jQuery dependency. Colorbox is a jQuery plugin β€” it cannot run without it. Drupal core has been progressively reducing its own reliance on jQuery, and many performance-conscious themes load jQuery lazily or not at all. A hard jQuery dependency works against that goal.
  • Aging UI and animations. The default Colorbox styles feel dated compared to 2024–2026 design norms. Heavily customizing its CSS is often needed just to reach a baseline modern look.
  • Accessibility gaps. While Colorbox has received some accessibility patches over the years, it was not designed with WCAG 2.1 AA as a primary goal. Focus trapping, ARIA roles, and screen-reader announcements can require substantial extra work.
  • Maintenance velocity. The upstream jQuery Colorbox library receives infrequent updates. For a long-lived Drupal project, betting on a slowly maintained dependency introduces risk.

2.2 Advantages of GLightbox

GLightbox addresses each of the above pain points directly:

  • Zero dependencies. Pure ES6+ JavaScript; no jQuery required.
  • Modern UX. Smooth CSS transitions, swipe gestures, keyboard navigation, and a clean default theme that integrates well with contemporary designs.
  • First-class accessibility. Focus is trapped inside the lightbox, keyboard arrow-key navigation works out of the box, and proper ARIA role="dialog" semantics are applied automatically.
  • Lightweight. The minified + gzipped bundle is under 15 KB β€” roughly 3Γ— lighter than a typical Colorbox setup.
  • Gallery grouping. Native support for grouped galleries using a data-gallery attribute, without requiring additional plugins.
  • Active development. The GLightbox project on GitHub sees regular releases and bug fixes.
Feature / CriterionColorboxGLightbox
jQuery dependencyRequiredNone
Bundle size (min+gz)~40 KB~14 KB
Responsive / mobile swipePartialYes
ARIA / focus trappingLimitedFull
Native gallery groupingVia pluginBuilt-in
Video (YouTube/Vimeo/inline)YesYes
Drupal module availableYesYes
Active upstream maintenanceSlowActive

3 Drupal Ecosystem Overview

Drupal core has been on a multi-year journey to reduce its jQuery footprint, moving toward vanilla JS and modern browser APIs. This is reflected in the deprecation of many jQuery-based behaviors in Drupal 10+ and the push for themes to adopt leaner JavaScript strategies.

On the contrib side, both Colorbox and GLightbox have dedicated Drupal modules on Drupal.org:

  • colorbox β€” the classic choice, with deep integration into Image field formatters, Views, and the media system. Still widely installed but receiving fewer updates.
  • glightbox β€” a newer contrib module wrapping the GLightbox JS library. Provides Image and Media field formatters, Views support, and a settings form for common GLightbox options.
πŸ’‘ Module vs Custom Integration Using the glightbox Drupal module is the right choice for most sites β€” it handles library attachment, field formatter configuration, and cache integration. A custom integration (manually attaching the library and writing Drupal behaviors) is only preferable when you need highly specialized behavior that the module does not expose.

4 Preparing for the Migration

4.1 Audit Current Colorbox Usage

Before touching any configuration, build a complete picture of where and how Colorbox is used in your site:

  1. Image fields. Visit Structure β†’ Content Types β†’ [Type] β†’ Manage display for every content type and check whether any image field uses the Colorbox formatter. Note the image styles and caption settings.
  2. Media entities. Check media type display modes under Structure β†’ Media types. Repeat for each media type that involves images or video.
  3. Views. Search for Views that include image fields and verify the field formatter in use. Colorbox may also be applied via the Views "Colorbox" format plugin.
  4. Custom code. Search your custom modules and themes for references to colorbox, .colorbox, Drupal.behaviors.colorbox, and the library key colorbox/colorbox.
# Quick search across your codebase (run from Drupal root)
grep -r "colorbox" web/modules/custom web/themes/custom \
  --include="*.php" --include="*.js" --include="*.twig" \
  --include="*.yml" -l

Keep a note of every location found. You will revisit each one during the replacement phase.

4.2 Backup and Environment Considerations

⚠️ Always work on a non-production environment first. Perform the migration on a local or staging environment, verify it fully, then deploy configuration changes via drush config:export and drush config:import.
  • Export active configuration: drush config:export
  • Commit the export to version control before starting
  • Disable CSS/JS aggregation during the migration (Admin β†’ Performance)
  • Take a database dump: drush sql:dump > pre-migration.sql
  • Ensure your deployment pipeline can push config changes to staging/production

5 Installing and Enabling GLightbox in Drupal

5.1 Install the GLightbox JavaScript Library

The Drupal GLightbox module depends on the upstream GLightbox JS library. There are two supported ways to provide it.

Option A β€” Composer + Asset Packagist (Recommended)

# Add Asset Packagist as a repository (once per project)
composer config repositories.asset-packagist \
  composer https://asset-packagist.org

# Require the library
composer require oomphinc/composer-installers-extender
composer require npm-asset/glightbox

Add or confirm the installer path for npm-asset in your composer.json extra.installer-paths section:

"extra": {
  "installer-types": ["npm-asset", "bower-asset"],
  "installer-paths": {
    "web/libraries/{$name}": [
      "type:drupal-library",
      "type:npm-asset",
      "type:bower-asset"
    ]
  }
}

After running composer install, the library will land at web/libraries/glightbox/.

Option B β€” Manual Placement

Download the latest release from the GLightbox GitHub releases page and place the contents so the following paths exist:

web/libraries/glightbox/dist/js/glightbox.min.js
web/libraries/glightbox/dist/css/glightbox.min.css

5.2 Install and Enable the GLightbox Drupal Module

# Download the module
composer require drupal/glightbox

# Enable it
drush en glightbox -y

# Clear caches
drush cr

Navigate to Admin β†’ Configuration β†’ Media β†’ GLightbox to confirm the library is detected and to explore the global configuration options.

πŸ’‘ Module Version Compatibility Check the glightbox module page on Drupal.org for the version compatible with your Drupal core. As of early 2026, the 1.x branch supports Drupal 9–11.

6 Replacing Colorbox Functionality

6.1 Image Fields

This is the most common Colorbox use case: an image field on a content type displaying a thumbnail that opens the full-size image in a lightbox.

  1. Go to Structure β†’ Content Types β†’ [Your Type] β†’ Manage display.
  2. Locate the image field. Click the Format dropdown and change it from Colorbox to GLightbox.
  3. Click the settings gear (βš™) to configure the formatter. Set the Image style (thumbnail shown on the page) and the Linked image style (image loaded inside the lightbox). Enable captions if desired.
  4. Save the display configuration and clear caches: drush cr.

You can also perform this configuration export and apply it via YAML. An example field formatter configuration in a content type display YAML:

# core.entity_view_display.node.article.default.yml (excerpt)
dependencies:
  module:
    - glightbox
    - image
content:
  field_image:
    type: glightbox
    label: hidden
    settings:
      image_style: medium
      image_link: ''
      glightbox_image_style: large
      glightbox_gallery: ''
      glightbox_caption: title
      glightbox_caption_custom: ''
    third_party_settings: {  }

6.2 Media and Galleries

For sites using Drupal's Media system, the migration steps are similar but applied to Media type display modes.

  • Visit Structure β†’ Media types β†’ [Type] β†’ Manage display.
  • Switch the image source field formatter from Colorbox to GLightbox.
  • For gallery grouping, configure the Gallery ID field in the GLightbox formatter settings. All items sharing the same gallery ID will be navigable as a group inside the lightbox. This maps directly to GLightbox's native data-gallery attribute.
ℹ️ Gallery IDs and Context If you need images from the same node to form one gallery, use a static gallery ID like node-gallery. If images from different entities must be isolated, use a token-based ID such as gallery-[node:nid] (requires the Token module).

Caption mapping is straightforward: GLightbox reads the data-description attribute. The Drupal module lets you map this to the image's title or alt attribute, or to a custom field value.

6.3 Views Integration

If Views are displaying images with Colorbox formatting, update each View as follows:

  1. Open the View in Structure β†’ Views β†’ [View name] β†’ Edit.
  2. Under Fields, click the image field. In the Formatter dropdown, switch from Colorbox to GLightbox.
  3. If the Colorbox integration was handled at the Format level (e.g., a "Colorbox" format plugin), switch to a standard format such as Unformatted list or Grid and apply the GLightbox formatter at the field level instead.
  4. Save and clear caches.

7 Removing Colorbox Safely

Once all formatters and custom code have been migrated, you can safely remove Colorbox. Follow this order to avoid dependency errors:

  1. Disable the Colorbox module. Disabling before uninstalling allows Drupal to run its hook_uninstall() cleanup.

    drush pm:uninstall colorbox -y
  2. Remove from composer.json.

    composer remove drupal/colorbox
  3. Remove the Colorbox JS library from web/libraries/colorbox/ if it was placed manually.
  4. Clean up custom code. Search for and remove any remaining references to Colorbox CSS classes (.colorbox, .colorbox-load), JavaScript behaviors (Drupal.behaviors.colorbox), or library attachments (colorbox/colorbox).
  5. Clear all caches and export config.

    drush cr
    drush config:export
⚠️ Check for orphaned configuration Run drush config:status after uninstalling. If Colorbox left behind orphaned config entities (e.g., in field formatter settings that were never updated), you may see warnings. Address these by manually editing the relevant YAML files in your config sync directory.

8 Customization and Enhancements

8.1 GLightbox Configuration Options

The global GLightbox settings page (Admin β†’ Configuration β†’ Media β†’ GLightbox) exposes the most commonly needed options. These correspond directly to GLightbox's JavaScript API:

OptionDescriptionDefault
animationOpening/closing transition: zoom, fade, nonezoom
autoplayVideosAuto-play video when the lightbox openstrue
loopLoop through gallery itemsfalse
touchNavigationEnable swipe navigation on touch devicestrue
keyboardNavigationArrow key navigation between itemstrue
closeOnOutsideClickClose when clicking outside the mediatrue
width / heightDefault overlay dimensions (images auto-size)900px / 506px

8.2 Theming and Styling

GLightbox ships with a default stylesheet (glightbox.min.css) that provides a clean dark-overlay design. Override it in your theme without modifying the library file:

/* mytheme/css/glightbox-overrides.css */

/* Change overlay background */
.glightbox-clean .goverlay {
  background: rgba(0, 0, 0, 0.92);
}

/* Style the caption area */
.glightbox-clean .gdesc-inner {
  font-family: inherit;
  font-size: 0.9rem;
  color: #f0f0f0;
  padding: 12px 16px;
}

/* Enlarge navigation arrows */
.glightbox-clean .gnext,
.glightbox-clean .gprev {
  width: 48px;
  height: 48px;
}

/* Light-mode variant */
@media (prefers-color-scheme: light) {
  .glightbox-clean .goverlay {
    background: rgba(255, 255, 255, 0.95);
  }
  .glightbox-clean .gdesc-inner {
    color: #1a1a1a;
  }
}

Attach the override stylesheet in your theme's .libraries.yml:

# mytheme.libraries.yml
glightbox-overrides:
  version: VERSION
  css:
    theme:
      css/glightbox-overrides.css: {}
  dependencies:
    - glightbox/glightbox

Then attach it globally in mytheme.info.yml:

# mytheme.info.yml (excerpt)
libraries:
  - mytheme/glightbox-overrides

8.3 Advanced Use Cases

Programmatic Attachment via #attached

You can attach the GLightbox library to any render array in a custom module or preprocess hook:

// In a preprocess function or custom block build()
$build['#attached']['library'][] = 'glightbox/glightbox';

// Pass configuration overrides to JS settings
$build['#attached']['drupalSettings']['glightbox'] = [
  'animation'  => 'fade',
  'loop'       => TRUE,
  'touchNavigation' => TRUE,
];

Custom Triggers in Twig Templates

To manually create a GLightbox trigger in a Twig template, add the correct attributes. GLightbox picks up any element with class="glightbox" (or your configured selector):

{# Open a single image #}
<a href="{{ file_url(node.field_hero_image.entity.uri.value) }}"
   class="glightbox"
   data-title="{{ node.label }}"
   data-description="{{ node.field_caption.value }}">
  {{ content.field_hero_image }}
</a>

{# Gallery group β€” all items with the same data-gallery open together #}
{% for item in node.field_gallery %}
  <a href="{{ file_url(item.entity.uri.value) }}"
     class="glightbox"
     data-gallery="gallery-{{ node.id }}"
     data-description="{{ item.alt }}">
    <img src="{{ file_url(item.entity.uri.value) | image_style('thumbnail') }}"
         alt="{{ item.alt }}" />
  </a>
{% endfor %}

Drupal Behavior for Custom Initialization

If you need to initialize GLightbox with options not exposed by the module's admin UI, use a custom Drupal behavior:

// mytheme/js/glightbox-init.js
(function (Drupal, drupalSettings) {
  'use strict';

  Drupal.behaviors.mythemeGlightbox = {
    attach(context, settings) {
      // Only initialize once per context
      const elements = context.querySelectorAll('.glightbox-custom:not(.glightbox-processed)');
      if (!elements.length) return;

      elements.forEach(el => el.classList.add('glightbox-processed'));

      const lightbox = GLightbox({
        selector: '.glightbox-custom',
        touchNavigation: true,
        loop: true,
        animation: 'fade',
        autoplayVideos: settings.glightbox?.autoplayVideos ?? true,
      });
    },
  };

}(Drupal, drupalSettings));

9 Testing and Quality Assurance

After completing the migration, run through the following QA checklist before deploying to production:

Functional Testing

  • Images open in the lightbox on click across all affected content types
  • Gallery navigation (prev/next arrows, keyboard arrows) works correctly
  • Captions display and match the expected field value
  • Video items (YouTube, Vimeo, local) autoplay and close correctly
  • Closing the lightbox (βœ• button, Escape key, outside click) restores focus

Cross-Browser Testing

  • Chrome/Edge (Chromium), Firefox, Safari (macOS and iOS)
  • Verify CSS transitions render correctly in all tested browsers

Mobile and Touch Testing

  • Swipe left/right to navigate gallery items
  • Pinch-to-zoom on images (if enabled)
  • Overlay correctly covers viewport on small screens

Accessibility Checks

  • Tab key cycles through lightbox controls (close, prev, next)
  • Focus returns to the trigger element after closing
  • Screen reader announces the dialog and its content (test with NVDA or VoiceOver)
  • Run axe DevTools or Lighthouse accessibility audit β€” target zero critical errors

Performance

  • Re-enable CSS/JS aggregation and verify GLightbox still initializes
  • Run a Lighthouse performance audit and compare with the Colorbox baseline
  • Confirm no JavaScript console errors on any tested page

10 Common Issues and Troubleshooting

Images Not Opening in the Lightbox

Symptom: Clicking the image navigates to the linked URL instead of opening GLightbox.

  • Verify the GLightbox library is loading: open browser DevTools β†’ Network tab, filter for glightbox. If missing, check that the library files exist at web/libraries/glightbox/dist/.
  • Ensure CSS/JS aggregation is working correctly; try disabling it temporarily to isolate aggregation-related issues.
  • Check the rendered HTML to confirm the trigger element has the class="glightbox" attribute (or the custom selector you configured).

Missing Captions or Broken Galleries

Symptom: Captions are empty or gallery navigation skips items.

  • Inspect the rendered anchor tags: verify data-description is populated and data-gallery values match across grouped items.
  • Check that the Caption source field formatter setting points to a non-empty field.
  • For gallery grouping, confirm the gallery ID is consistent; token-generated IDs may resolve to empty strings if the token module is not installed.

Conflicts with Other JS Libraries

Symptom: GLightbox partially initializes or throws console errors.

  • Check for duplicate GLightbox library loads (module + manual theme attachment).
  • Verify that no other library is overriding window.GLightbox.
  • If your theme uses a JS bundler, ensure GLightbox is not bundled separately in addition to being attached via Drupal's asset system.

Cache and Aggregation Issues

Symptom: GLightbox works in development but breaks in production.

  • Run drush cr on production after deploying config changes.
  • Verify that web/libraries/glightbox/ is committed or deployed correctly β€” it is sometimes excluded by .gitignore rules targeting the libraries/ directory. Consider using composer install --no-dev in your CI/CD pipeline to ensure the library is placed.
  • If CSS aggregation compresses the GLightbox stylesheet in a way that breaks selector specificity, add your override file later in the asset loading order.
# Clear all caches on production (if Drush is available)
drush @prod cr

# Verify the library file is in place
ls web/libraries/glightbox/dist/js/glightbox.min.js

11 Conclusion

Migrating from Colorbox to GLightbox is a meaningful frontend modernization step for any Drupal project. The benefits are tangible:

  • Eliminate the jQuery runtime dependency from your lightbox path
  • Deliver a faster, lighter experience to your visitors
  • Gain out-of-the-box accessibility compliance without custom patches
  • Align with Drupal core's direction toward vanilla JavaScript
  • Reduce long-term maintenance burden with an actively developed library

The migration itself is low-risk when approached methodically: audit first, migrate field formatters one by one, clean up legacy code, and test thoroughly before deploying. The glightbox Drupal module makes most of this declarative β€” configuration changes in the admin UI rather than custom code.

For sites doing a broader frontend modernization β€” moving toward a decoupled or headless architecture, adopting a modern theme (Olivero, Gin, or a custom design system), or reducing JavaScript weight β€” replacing Colorbox with GLightbox is an excellent, contained starting point that delivers visible results with minimal risk.

πŸš€ What's Next? After completing this migration, consider auditing other jQuery-dependent contrib modules. Tools like drush pm:list --filter=status=enabled combined with a dependency check can surface additional candidates for modernization.
 
Technical and architectural inquiries
Ivan Abramenko, Principal Drupal Architect
ivan.abramenko@drupalbook.org
Project inquiries
projects@drupalbook.org