Small win - mouse hover event

I have a custom component and wanted to add a mouse hover event to it. Couldn’t find this particular situation in the docs or forums. Everything about event listeners is geared towards custom HTML components.

Normally, I’d use CSS to add a hover effect but I wanted to use hover on one component (the link/columnpanel container) to make another sub-component do something (make the title bold).

So I made a custom component and added a ‘mouseover’ and ‘mouseout’ event listener on the outer component (in this case it is a link).

No javascript and no custom HTML!

from ._anvil_designer import IconCardTemplate
from anvil import *
import anvil.js


class IconCard(IconCardTemplate):
    def __init__(self, **properties):
        # Set Form properties and Data Bindings.
        self.init_components(**properties)
        dom_node = anvil.js.get_dom_node(self.link_card)
        dom_node.addEventListener('mouseover', self.mouseover_event)
        dom_node.addEventListener('mouseout', self.mouseoff_event)

    def mouseover_event(self, sender, **event_args):
        self.lbl_title.bold = True
            
    def mouseoff_event(self, sender, **event_args):
        self.lbl_title.bold = False

Export-1718221469888

6 Likes

Nice Work!

This can also be acheived with the anvil_extras augment library (see below).

from anvil_extras import augment
augment.set_event_handler(self.lbl_title, 'hover', self.lbl_title_hover)
# equivalent to
# augment.set_event_handler(self.link, 'mouseenter', self.link_hover)
# augment.set_event_handler(self.link, 'mouseleave', self.link_hover)
# or
# augment.set_event_handler(self.link, 'mouseenter mouseleave', self.link_hover)

def lbl_title_hover(self, **event_args):
   self.lbl_title.bold = 'enter' in event_args['event_type']

augment is great to add custom events to any component!

6 Likes

anvil-extras is the gift that keeps on giving

5 Likes