Custom Color Component

I tried to add a change event to the color picker. It doesn’t work, and I don’t understand why.

In the custom html:

<input type = 'color' id = "choosecolor" onchange="color_changed_event()">
  
<script>
function color_changed_event() {
  anvil.call(this,"my_change_func", "color changed")
}
</script>

Inserting window.print() in ‘color_changed_event’ confirms that this is actually called. But I never get to my python method in the code of the custom html form:

  def my_change_func(self, msg):    
    print('color changed')
    self.raise_event('x-color-changed')

Here is the clone link: Anvil | Login

Can anyone see what I’m doing wrong?

Just a wild stab here, but does it work when you remove the ()?

I think the problem is your this argument

<input type = 'color' id = "choosecolor" onchange="color_changed_event(this)">

<script>
function color_changed_event(color_input) {
  anvil.call(color_input, "my_change_func", "color changed")
}
</script>

If you ever want to move into the anvil.js interop world:

In html:

<input type='color'>

In python:

import anvil.js

class colorpicker(colorpickerTemplate):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    dom_node = anvil.js.get_dom_node(self)
    self.color_node = dom_node.querySelector("input")
    self.color_node.onchange = self.color_changed

  def color_changed(self, js_event):
    self.raise_event("x-color_changed", color=self.color_node.value)
1 Like

Removing () or inserting (this) in onchange="color_changed_event()" did not solve it, but helped me find out that I had to use a specific DOM element instead of “this”:

function color_changed_event() {
  var x = document.getElementById("choosecolor");
  anvil.call(x,"my_change_func", "color changed")
/# didn't work: anvil.call(this,"my_change_func", "color changed")  /#
}

But I much preferred @stucork’s solution of having one line in the custom html and the rest in python code. This is how I will do things from now on. Thanks for educating me!

I updated the app with @stucork’s solution, and kept the other in there as well for reference.

Repost of the clone link:
https://anvil.works/build#clone:HCA2EXWWISWRDHOA=SYSSOGZ3EWQXXGRHAUP5QLYW