On right click event

Pretty self explanatory. I’d like an on_right_click event function to be available on components.

1 Like

Just thought I’d share this since I’m here…

You can use JavaScript to do this, and it works very simply the way I’ve done it.

You will need to use a bit of Custom HTML within the form with <script> in it, here’s an example. This is all self-contained, no JS libraries or anything.

<div id='h'>hi</div>

<script>
document.getElementById('h').addEventListener('contextmenu', function(){
   alert('hi')
})
</script>

FYI if u don’t know already contextmenu is JavaScript’s right click event - but it also works for ctrl+click and other evs that would trigger a context menu.

You should be able to add this to your existing forms - in Properties on the right bar, change the html property to ‘Custom HTML’, click Edit next to it, add code similar to the above. Obviously you will need to change the alert('hi') part, this is just to demo it - and unfortunately I haven’t found a way to call Python with this, but it’s a start.

Here’s a clone you might want to check out:
https://anvil.works/build#clone:CF662ZSI6BEPMBCW=TGZ6DL26KZFEZAOMMM7I5DWX

Hope I have (if only slightly) helped!

3 Likes

@viggobryantfrost ,

Thank you for that post, I’m not a big JavaScript fan (Hence why I think a lot of people are using Anvil ;), I appreciate your effort in helping with your code! Hoping the Anvil staff sees this and implements it into Anvil native :slight_smile:

There isn’t a native way to do this but you can use the anvil.js as a work around.

import anvil.js

    dom_node = anvil.js.get_dom_node(my_component)
    dom_node.addEventListener('contextmenu', self.right_click)

  def right_click(self, e):
    e.preventDefault() # stop the default context menu
    alert('right click')

3 Likes

This was really helpful but I could not figure out how to get the sender of this right click event. Would be really useful for me when making references

I’d use functools partial here. I’ve not tried it but I think it will work.

from functools import partial
import anvil.js


    dom_node = anvil.js.get_dom_node(my_component)
    dom_node.addEventListener('contextmenu', partial(self.right_click, sender=my_component))

  def right_click(self, e, sender):
    e.preventDefault() # stop the default context menu
    alert('right click')
    

It works. Thank you so much.

1 Like