The <random-choice>
element
(One of the custom elements I use around here.)
The <random-choice>
element can be used to display one1 element from a collection of elements, when you don’t really care which one gets displayed.
As with any custom element, the close tag cannot be omitted.
<random-choice>…</random-choice>
The element should have N children:
<random-choice>
takes multiple children<random-choice>
<span>foo</span>
<span>bar</span>
<span>baz</span>
<span>quux</span>
</random-choice>
All but one1 of them should be marked hidden=""
:
<random-choice>
<span>foo</span>
<span hidden>bar</span>
<span hidden>baz</span>
<span hidden>quux</span>
</random-choice>
(This way, even if the script that defines the custom element never runs, the user experience approximates what the author intended. See HTML web components for more.)
The above snippet gets rendered like this:
Try reloading the page and see what happens. Notice that the chosen child element never changes. Why? Well, the choice is only changed when the element’s choose()
method is called, and by default, that method is never called.
Why not? Well, mostly because I couldn’t decide on a sensible default. For a simple static page, perhaps simply calling it once from a DOMContentLoaded
handler is the right thing. But some other page may want some more complex behavior, so I decided to simply expose the functionality as a method call and let adopting sites call it how- and whenever they’d like.
For the purposes of this demo, I’ve added a click
handler like so:
click
handler that calls choose()
document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll("random-choice").forEach(
el => el.addEventListener("click", evt => el.choose()));
});
Go ahead and click on the <random-choice>
element in Example 1 to see it in action.
The choose()
method works by setting or removing the hidden=""
attribute on the element’s children.
I lied a bit above when I said it only picks one of the children. You can specify how many to pick with the how-many=""
attribute. The default is 1.
<random-choice how-many=2>
<span>foo</span>
<span>bar</span>
<span hidden>baz</span>
<span hidden>quux</span>
</random-choice>
Note how I’ve left the hidden=""
attribute off of two of the children, so that the right number of children are visible if JavaScript is disabled.
The above snippet gets rendered like this:
When multiple children are displayed, they appear in document order.
The settable howMany
property reflects the how-many=""
content attribute.