简体   繁体   中英

How can I run javascript in rails webpage

I am creating a webpage with rails and I'm trying to run baguetteBox.js to create an image gallery. I've tried using <%= javascript_pack_tag 'gallery' %> at the top of the gallery page along with baguetteBox CSS and js script but it still not works. Hope that you can help me, thank you.

if in your javascript you are looking from an element to mount on or change on click it has to be imported after the html with the same tag just at the end of the body

To install baguetteBox need to run:

$ yarn add baguettebox.js

then you can create a file app/javascript/js/gallery.js with the following:

import baguetteBox from 'baguettebox.js';

# If you are not using turbolinks replace 'turbolinks:load' with 'DOMContentLoaded'
document.addEventListener('turbolinks:load', () => {
    baguetteBox.run('.gallery');
})

then you can import that into your application.js file like so:

...
import '../js/gallery'

That should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM