Adding a click event to a card component

What I’m trying to do: I wan to add a click event to a card component. I’ve read the document on custom component and custom events but its not clear how to achieve what I want.

What I’ve tried and what’s not working: I’ve tried to set the click event on a card component using the add_event_handler function but its throwing the error: " Cannot set event handler for unknown event ‘click’ on undefined component. Custom event names must start with ‘x-’. at [Form1, line 21](javascript:void(0))" .

Code Sample:

# code snippet

Clone link:
share a copy of your app

Hi @edmondssesay and welcome to the forum,

Have you added the event name to the list of custom events for your custom component - see the section of the docs below.

Anvil Docs | Custom Components

if that doesn’t help - please share a clone of your app so that others can help debug.

Hi, Yes,. I’ve tried that. See source code. I want the a print message to show when the embedded card is clicked. But it’s not working

your custom component needs to raise the click event somewhere. Currently the custom component doesn’t raise the click event. Since it doesn’t raise a click event then the click event will never fire, and so your function custom_form_1_click will never have a click event to handle.

to raise an event use

self.raise_event('click')

This might also help making a card clickable

1 Like

Your second suggestion works well for what I needed. Thanks so much.

Your first suggestion of raising the click event on the init of the custom form raised the error " ValueError: Cannot raise event for unknown event ‘click’ on undefined component. Custom event names must start with ‘x-’. at [CustomForm, line 10](javascript:void(0))". For my education, could you explain how best to resolve this? thanks again!

very slightly adapted version
https://anvil.works/build#clone:Z5CDQJSN4R6U4ERC=ADXXF4LEBTQRJDIT2EFLRPDW

The custom component is wrapped in a link and raises a click event when its clicked.
This is then handled by the main form as before

3 Likes

So simple, yet so clever :slight_smile: Solved my problems.