Skip to content

Color Picker

Modern browsers have the ability to add a simple color picker directly to your HTML, using <input type="color"> If your browser supports one, it looks like this:

The html for this element looks like this:

<input type="color" id="main-color">

There are several events one can listen to react to the user changing color, including:

  • click - fires when the user first clicks on the element to open the color picker
  • input - fires whenever the user selects a new color within the color picker
  • change - fires when the user deselects/closes the color picker

To listen for these events in PyScript, add an attribute called py-[event] to the input object, where [event] is the type of one of these events above.

For example, the following code prints:

  • An acknowledgement that the user opened the color picker
  • The selected color whenver the color is changed
  • The 'final' selected color when the color picker is closed

<input type="color" 
    id="main-color" 
    py-click="opened_picker"
    py-input="color_changed" 
    py-change="final_color">
from pyscript import display, document

def opened_picker(*args):
    display("You opened the color picker!")

def color_changed(*args):
    elem = document.getElementById("main-color")
    value = elem.value
    display(f"The color changed to: {value}")

def final_color(*args):
    elem = document.getElementById("main-color")
    value = elem.value
    display(f"The selected color is: {value}")

To listen for these events in Pyodide, once Pyodide is loaded,, use Pyodide's add_event_listener function to attach the appropraite event listeners to the <input> element.

For example, the following code prints:

  • An acknowledgement that the user opened the color picker
  • The selected color whenver the color is changed
  • The 'final' selected color when the color picker is closed
<input type="color" id="main-color" >

The following Python code should be run using pyodide.runPython:

import js
from pyodide.ffi.wrappers import add_event_listener

def opened_picker(event):
    print("You opened the color picker!")

def color_changed(event):
    value = event.target.value
    print(f"The color changed to: {value}")

def final_color(event):
    value = event.target.value
    print(f"The selected color is: {value}")

elem = js.document.getElementById("main-color")
add_event_listener(elem, 'click', opened_picker)
add_event_listener(elem, 'input', color_changed)
add_event_listener(elem, 'change', final_color)