cybrkyd

How to include simple Javascript within Hugo

 Sat, 03 Feb 2024 10:21 UTC
How to include simple Javascript within Hugo
Image: CC BY 4.0 by cybrkyd

I had a bit of a battle in trying to figure out how to add a simple “back-to-top” Javascript button to Hugo. There is not much help to be found at discourse.gohugo.io therefore I’m adding this to my knowledge base for future reference.

I will be using the button from https://github.com/vfeskov/vanilla-back-to-top.

Steps in Hugo

  1. Make a new folder in `/static`; I made a new folder named `js`.
  2. Create a new file called `toppy.js` and add the following to it:
    addBackToTop({
      diameter: 56,
      backgroundColor: 'rgb(250,76, 76)',
      textColor: '#fff'
    })
    
  3. Download the file vanilla-back-to-top.min.js and save it to `/static/js`. My theme is a heavily customised version of beautifulhugo so I just tend to do things directly in my themes folders.
  4. Edit `/layouts/partials/footer.html` and link back to the two JS files. Add these two lines to the bottom:
    <script defer language="javascript" type="text/javascript"  src="{{ "/js/vanilla-back-to-top.min.js" | urlize | relURL }}"></script>
    <script defer language="javascript" type="text/javascript"  src="{{ "/js/toppy.js" | urlize | relURL }}"></script>
    

The button is now live. I wanted two quick customisations so I made my changes.

  1. In my css, I added a bit of opacity to the button:
    #back-to-top{opacity:0.7}
    
  2. In `vanilla-back-to-top.min.js`, I increased the scroll depth before the button appears on-page from 1px to 1000px. Locate this entry:
    M=void 0===T?1:T
    
    and change it to:
    M=void 0===T?1000:T
    
»
Tagged in: #Hugo #JavaScript

Visitors: Loading...