Clickable things revisited

I followed the great instructions for placing cards in links to create clickable components:

https://anvil.works/forum/t/adding-a-click-event-to-a-card-component/8949

Then I sort of tripped and fell into a slightly different answer because when you have lots of things inside the clickable card, it can get messy really quickly. Just wanted to share in case it saves anyone else a headache in future.

For ease make you have your imports done at the top of your form:

from anvil.js import window
import anvil.js

Get the dom node of the thing you want to click inside your card:

theclickything = anvil.js.get_dom_node(self.thingiwanttoclick)
theclickything.addEventListener('click',self.click_event)

Set up your click_event function:

def click_event(self, event, **event_args):
    event.stopPropagation()
    url = event.target.getAttribute("href")
    if url is not None:
      if "https://my-anvil-app/#?" in url:
        #Do something with url hash in your app
        query_params = anvil.get_url_hash()
        if query_params:
          searched = query_params.get("search")
          if searched:
            alert(content=MyPopUp(searched=searched),large=True,buttons=[("Close")])
            window.history.pushState("", "", "/")
          else:
             window.history.pushState("", "", "/")
            #Do something else
      elif url.startswith("https://") and "https://my-anvil-app/#?" not in url:
        #Send the user to a new tab to see something else
        window.open(url, "_blank")
      else:
        window.history.pushState("", "", "/") 
       #Do something else
    else:
      window.history.pushState("", "", "/")
      #Do something else

If you’ve ever used get url hash, you’ll know that your browser bar has the has url forever after it’s there, so the line window.history.pushState(“”, “”, “/”) just takes that back to your app. It’s a tidiness thing (if you’re a bit obsessive like me!)

Anyway, just wanted to share as it’s saved me a lot of grief.