Problem
I'd like to add a small bit of client-side JavaScript to my Eleventy website. I can't seem to access document.
using Eleventy which means I can't access elements and listen to them for events. Example of what doesn't work:
const formElement = document.querySelector("form")
The error message I receive from Eleventy:
ReferenceError: document is not defined
Question
How do I work with Eleventy in order to listen to document element changes and make page changes?
Example:
formElement.addEventListener("change", function () {
// Update nearby paragraph element based on form value
});
My real-world scenario: I would like to have a paragraph element display which of the form
's input type="radio"
has the value checked
.
Approach so far
I have a file in /data called fruits.json:
{
"items": [
{
"name": "Apple"
},
{
"name": "Banana"
},
{
"name": "Strawberry"
},
{
"name": "Mango"
},
{
"name": "Peach"
},
{
"name": "Watermelon"
},
{
"name": "Blueberry"
}
]
}
And a HTML file in /_includes/layouts based on my base.html file:
{% extends "layouts/base.html" %}
{% block content %}
<form>
{% for item in fruits.items %}
{# Create a radio button for each, with the first one checked by default #}
<input type="radio" name="screen" id="{{ item.name | slug }}" value="{{ item.name | slug }}" {% if loop.index === 1 %} checked {% endif %}>
<label for="{{ item.name | slug }}">{{ item.name }}</label>
{% endfor %}
{% set selectedFruit = helpers.getSelectedFruit() %}
<p>Currently selected item from above is: {{ selectedFruit }}</p>
</form>
{% endblock %}
Note that thee variable called selectedFruit
is assigned to a helper function:
{% set selectedScreen = helpers.getSelectedScreen() %}
That getSelectedScreen()
function looks like:
getSelectedScreen() {
const formEl = document.querySelector("form")
console.log(formEl)
}
Aside from not being able to work with .document
, I feel like this approach is probably 'against the grain' of Eleventy, static site generators in other ways:
- The script is being called mid-document
- The script is one-off and away from its context
I wonder if I'm approaching this wrong in the first place, or if I just need to do something to allow .document
access.