My kid is in a little phase where word search puzzles are really fun. She likes doing them, and then possibly because we share blood, she immediately started to want to make them. I figured it would be a fun little recreational coding job to build a maker, so I did that: Word Search Puzzle Maker. It’s not fancy, you just write in your words then a button click will fill in the un-filled spaces with random letters and you’re good to print it out.
One of the configuration options for the “maker” is how big you want to build the grid. A 10×10 grid is the default, but it’s settable by just setting a variable in one place.
It turns out it’s useful to have this variable in all three of the important front-end technologies at play: the HTML, CSS, and JavaScript. The relevant variable here is size
, which represents the number of cells across and tall the grid is.
- HTML — Well, Pug, actually. Pug generates HTML, and having the
size
there means I can write a loop that generates the number of elements in the grid the way I need. - CSS — Having the
size
there means I can set up the CSS grid with the appropriate columns/rows. - JavaScript — By having the
size
variable available there, I was able to implement arrow key navigation fairly easily which helped the experience of setting new words.
It all starts with that Pug code, so, ya know, sorry if that’s cheating. But here’s the rub:
- const size = 10;
script
| window.size = #{size};
| document.documentElement.style.setProperty('--size', #{size});
Code language: PHP (php)
The dash (-
) in that Pug code essentially means “this is JavaScript”, and the Node process that runs to create the HTML runs it. That means I can use the variable later to create the grid.
.grid
- for (let i = 0; i < size**2; i++)
.letter(data-index=i)
input(maxlength=1, matches="[A-Za-z]")
Code language: HTML, XML (xml)
The variable gets passed from Pug into client-side JavaScript by making a script tag and creating a variable off the window
object. A little variable interpolation makes that possible.
The variable gets passed to CSS in a similar fashion, using client-side JavaScript to call setProperty
on the documentElement
. That CSS custom property will then cascade to wherever we need it. I can use it on another element like this:
.grid {
display: grid;
grid-template-columns: repeat(var(--size), 1fr);
}
Code language: CSS (css)
That’s it really. I just got a kick out of setting a variable in one place and making use of it in three languages.
Try changing the size
above.