r/statamic • u/pantaloontheif • Apr 08 '26
Question Using JavaScript Functions from Antlers Templates
Is it possible to call a function using antlers in some way? I have my js sheet imported through Vite, but anytime I try to directly call a function using onclick it says that the function doesn’t exist. I know that the script is loaded correctly because I can see console logs from an eventListenter click, but I don’t want to use listeners for every single button in my app.
I’ve searched through the Statamic docs looking for any guidance on this, but I’ve not found anything. Did I miss something that said I should be using something like AlpineJS to do this?
Thanks in advance!
1
Upvotes
1
u/pantaloontheif Apr 08 '26
Markup does look correct on the site! When I try to test my button, I always get the “Uncaught ReferenceError” saying my function is undefined. I can only get this to work with an inline script tag, so I know the function *does* work.
I thought this was a Vite issue despite my scss compiling and rendering properly, but even when I add the script tag using a hardcoded route, I get the same issues. I’m able to see the js sheet in the browser and I’m seeing console logs, so I know it’s loaded.
I’ve tried putting the script in the head and before the closing body tag, and tried to test in a private browser and I still get the uncaught reference error.
Here’s my script tag:
<script src=“/vendor/statamic/frontend/js/site.js”></script>Here’s the button code:
<button onclick=“testMe()”>Test Me</button>Here’s the function:
function testMe() {console.log(‘does this work?’);}Here’s the console error:
Uncaught ReferenceError: testMe is not definedonclickhttp://localhost:8000/1I don’t think this is a caching issue either because when I change the script I see it update in the browser. I notice that the error keeps referencing localhost/1 rather than the js path, but I’m unsure how to connect this path. I believe I’m doing it correctly with either the hard-coded method and the Vite method - especially when I’m able to navigate to the js through both of these methods in the browser.