Lightbox2 with Rails 7.1 not initialising

126 Views Asked by At

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>
1

There are 1 best solutions below

1
Alex On BEST ANSWER
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();
});