Search code examples
javascriptnunjuckseleventy

Eleventy, Nunjucks, Tailwindcss, javascript toggle function to hide and display content


i have a static site using eleventy, tailwindcss, and nunjucks. this is my first time and overall really like it, but i still find the layout a bit confusing.

i would like to create a page of reusuable components, each component with two parts. example display of component,and then below it a div containing the components code to copy and paste.

in my /src/utils/ directory i added a simple toggle function to add and remove the class 'block' (tailwindcss)

i dont understand how to access that function in my /src/site/components.njk files code to add the functionality to my page.

numerous and lengthy google and duck duck go queries have not returned much info, so any and all help is appreciated


Solution

  • Since you want to have that functionality client-side, you need to make sure that your JavaScript is included in your site output. Since your /src/ directory only exists in your repository, it won't be available to the browser after your site has been built. The easiest way to make it accessible to the browser is to copy the JavaScript file to your output directory, then include it as a script in your HTML output. Make sure the URL matches the output location. For example, if your source file is /src/utils/component-toggle.js, your output directory is /dist/ and you copy the file to /dist/utils/component-toggle.js, the script tag should look like this:

    <script src="/utils/component-toggle.js" defer></script>
    

    See Passthrough file copy to learn how to copy static files during your build step.

    Make sure your JavaScript file works in a Browser context as well. For example, you can't use CommonJS (module.exports and require() syntax), since it's a NodeJS concept and doesn't exist in Browsers. If you use ES Module syntax (export default {} syntax), make sure it's supported in all browser your site supports.

    I've recently written a longer answer regarding this topic which explains why you have to do it this way as well as the difference between build-time and run-time JavaScript for static site generators, you can read it here if you want to know more.