My objective is to utilize the custom-select JavaScript library for managing dropdowns in blocks within the Wagtail Stream Field. While it's straightforward to implement this for regular fields when the DOMContentLoaded
event is triggered, I'm wondering if there is a specific event or hook for adding a block to the StreamField.
I attempted to call my function in the block's HTML template, but it seems to execute too early since styles are not applied to the selects in that HTML.
This is how my .js
file looks like (written in Typescript):
const initColorChoosers = () => {
const colorChoosers = Array.from(document.querySelectorAll('.color-chooser select')) as HTMLSelectElement[];
colorChoosers.forEach((chooser) => {
if (!chooser.hasAttribute('custom')) {
chooser.setAttribute("custom", "true")
new CustomSelect(chooser, {
customOptionClass: 'option--hero-glow-color'
})
}
})
}
document.addEventListener("DOMContentLoaded", function (event) {
window.myfuncs.initColorChoosers = () => initColorChoosers();
});
and here is my color chooser:
class Colors(blocks.ChoiceBlock):
choices = [
('color1', 'color1'),
('color2', 'color2'),
('color3', 'color3'),
]
required = False,
class Meta:
form_classname = 'color-chooser'
icon = 'copy'
The block template at the end includes this code:
<script>
window.myfuncs.initColorChoosers()
</script>
It works for previously added blocks but not for the current one. When I add a block with ColorChooser, the logic from custom-select
isn't applied. However, upon adding another block, the changes will be implemented for the first one.