Adding custom JavaScript code to the select option in a Wagtail choice block can be achieved by following

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.

Answer №1

To successfully implement a custom block in Wagtail, you must create a corresponding BlockAdapter (specific to the block type, such as StructBlockAdapter for a StructBlock) and a JavaScript BlockDefinition (again, tailored to the block type, like StructBlock -> StructBlockDefinition).

For more information, refer to the Wagtail documentation:

Additionally, you can follow this helpful guide on creating customized editor interfaces for Wagtail streamfield structblocks:

Remember that each time you add the block to the streamfield, Wagtail will load an instance of the BlockDefinition associated with it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Can you please provide instructions on how to retrieve images from an array and insert

I have a dropdown list with animal options: <select id="animal"> <option>Choose an animal </option> <option value="1">animal 1 </option> <option value="2">animal 2</option> <option value="3">animal 3 </op ...

Tips for incorporating ​ into every character of a text

Is there a way to automatically add a zero-width space after each letter in a text using React, similar to the example below? <h2> A&ZeroWidthSpace;L&ZeroWidthSpace;A&ZeroWidthSpace;N&ZeroWidthSpace; </h2> This is ...

Issue with Redux saga not responding to action initiated by clicking on an icon

Declaration of Saga function* DoStuffInSaga({myRef}){ try { console.info("saga running"); return yield delay(1000, 1); } catch(error){ console.warn(error); } } export function* mySaga(){ yield all([ yi ...

Python code malfunctioning only under a post request execution

My task involves executing a post request to initiate a child process for running my discord_bot.py script with the inclusion of a variable. The script runs smoothly when executed directly from the terminal; however, encountering crashes at a specific stag ...

Picking specific <button> items

Presented here are a series of buttons to choose from: <button id="hdfs-test" type="button" class="btn btn-default btn-lg">HDFS</button> <button id="hive-test" type="button" class="btn btn-default btn-lg">HIVE</button> <button id ...

What is the best way to implement a nested side menu in Ionic Framework?

Greetings! I'm currently attempting to incorporate a nested menu within a side menu. For instance, take a look at this example: http://codepen.io/ionic/pen/QwamEW When I select a menu item, a new page (new form) opens. However, I would like for th ...

The console displays "undefined" when formatting API data

I am attempting to format the data retrieved from an API since there is a lot of unnecessary information. However, when I try to display the formatted data in the console, it always shows as "undefined" or "null." I am importing and calling the fetch API ...

Similar to the app.get() method in Express, CasperJS provides a way

I have created a basic web scraping tool that extracts data from a website and displays it when I navigate to the URL - localhost:3434/page. This functionality was achieved using the express app.get() method. Now, I have a few inquiries: 1) I am curious ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...

D3 group of legendary elements

Is there a way to group both the circle and text elements for each legend item together? I'm currently facing a challenge with the enter/exit methods. While I can create the groups (g), I'm unable to append the text and circle elements. li.sel ...

React navigator appears stuck and unable to navigate between screens

I encounter an issue where my app closes when I press the switch screen button, but there is no error output displayed. I have checked for any version discrepancies and found no problem. The function I implemented for the button is functioning as expected ...

Inquiry into AngularJS data binding

Just dipping my toes into the world of Angular today. Found a tutorial at Angular JS in 30 mins This little project involves setting up basic databinding in Angular. The code features an input box that updates with whatever is typed next to it. As someone ...

Steps for iterating through an object and using an if statement to verify a property's value

My challenge involves filtering a property named 'miles' within an array of objects. The objective is to compare the 'miles' property value and only return those that are less than the user's specified miles. Subsequently, the valu ...

Accessing Google Analytics with a single OAuth token using the JavaScript API: A step-by-step guide

I'm currently developing a webpage for exclusive users to view shared Google Analytics data. I have managed to obtain an OAuth token for the account housing this data using JavaScript, but sadly it expires in just 1 hour. Is there a way to utilize th ...

Leverage variables from different Vue components and link them together

I'm currently working on two different sections of the website First: Is it acceptable to use one instance within another, particularly with v-model? Are there any drawbacks to this approach? Second: Is there a way to reference each other, such as p ...

"Seeking assistance with concept sharing and content transmission. In need of guidance

Basic Question I'm stuck trying to brainstorm a concept to reach my objective. I am having trouble figuring out how to navigate the DOM correctly with my chosen method. The Objective First, let me explain what I am doing: I use ajax to bring HTML ...

Navigating to a specific div within a component in Vuejs 2: Steps for routing

These are the routes I've set up for my application: const router = new VueRouter({ mode:'history', routes:[ { path:'/home', name:'home', component: Home }, { path: '/serv ...

Guide to sending checkbox data using jQuery AJAX

I am facing an issue with submitting the form below: <form action="/someurl" method="post"> <input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5"> <input type="checkbox" class="mychoice" name="name" value="appl ...

What is the best way to combine identical items in a JavaScript array?

I AM LOOKING TO COMBINE DUPLICATED ITEMS AND THEN DELETE THEM here is the sample array for testing: var arr = [{ 'id': 1, 'text': 'ab' }, { 'id': 1, 'text': 'cd' }, { 'i ...

Guide to transmitting webcam feed from server to servlet

I am trying to display the webcam connected to my server in a servlet. I have come across suggestions to use getUserMedia();, however, this only captures the user's video webcam feed and not the server's. Is there a way to achieve this? My servl ...