1

I'm trying to use the javascript library Lightbox2 with a rails 7.1 application.

config/importmap.rb:

pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"
pin "lightbox2", to: "lightbox2.js"

I've downloaded lightbox2.js and placed it in vendor/javascript directory.

There are no javascript console errors but when clicking on the link nothing happens - no errors reported just silence.

I suspect I need to somehow boot lightbox into life to look for it's data-lightbox tags but can't see how that's supposed to be done - do I need to add something into application.js?

I've tried adding various permutations from below to application.js but there's always an error stating that lightbox doesn't have any default exports (I checked and there aren't any) or that jQuery can't be found:

(This worked fine using UJS previously and rails 6.)

import "jquery"
import jQuery from 'jquery'

import "lightbox2"
Lightbox2.init()
import Lightbox from "lightbox2"

import lightbox from "lightbox2"
global.lightbox = lightbox

import "lightbox2"
import Lightbox2 from 'lightbox2'
application.register('lightbox2', Lightbox2)
<a data-lightbox="session_photos" href="fullres.jp">
   <img src="lowres.jpg">
</a>
2
  • works fine if i just do bin/importmap pin lightbox2 and import "lightbox2" Commented Feb 14, 2024 at 17:41
  • Just found an issue though. The lightbox effect stops working after following a link. This must be an issue with lightbox2 and turbo interaction I guess. After following a link, refreshing the page then clicking an image invokes the lightbox effect correctly, but using a link to another page then clicking an image doesn't invoke lightbox. Commented Feb 14, 2024 at 18:11

1 Answer 1

0
bin/importmap pin lightbox2

Since there are no page reloads you have to initialize lightbox on turbo:load events:

// app/javascript/application.js

import "jquery";
import lightbox from "lightbox2";

document.addEventListener("turbo:load", (event) => {
  lightbox.init();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Fab - very similar to the existing UJS logic. As most pages in this website don't have images I'll research using a stimulus controller to trigger the lightbox.init only on pages which contain an image. Thanks Alex for your patience with the recent issues I've been having migrating from rails 6 to 7.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.