Path: blob/main/doc/tutorials/expert/custom_js_components.md
2012 views
Creating a MarioButton with JSComponent
In this tutorial we will build a Mario style button with sounds and animations using the JSComponent feature in Panel. It aims to help you learn how to push the boundaries of what can be achieved with HoloViz Panel by creating advanced components using modern JavaScript and CSS technologies.

This tutorial draws heavily on the great ipymario tutorial by Trevor Manz.
Overview
We'll build a MarioButton that displays a pixelated Mario icon and plays a chime sound when clicked. The button will also have customizable parameters for gain, duration, size, and animation, showcasing the powerful capabilities of JSComponent.
Prerequisites
Ensure you have HoloViz Panel installed:
Step 1: Define the MarioButton Component
We'll start by defining the Python class for the MarioButton component, including its parameters and rendering logic.
Create a file named mario_button.py:
Explanation - Python
_esm: Specifies the path to the JavaScript file for the component._stylesheets: Specifies the path to the CSS file for styling the component._box: A parameter representing the pixel data for the Mario icon.gain,duration,size,animate: Parameters for customizing the button's behavior.pn.Param: Creates a Panel widget to control the parameters.
Step 2: Define the JavaScript for the MarioButton
Create a file named mario_button.js:
Explanation - JavaScript
chime: A function that generates the Mario chime sound using the Web Audio API.render: The main function that renders the button, sets up the canvas, handles click events, and manages parameter changes.
Step 3: Define the CSS for the MarioButton
Create a file named mario_button.css:
Explanation - CSS
.ipymario > canvas: Styles the canvas to ensure the Mario icon remains pixelated.@keyframes ipymario-bounce: Defines the bounce animation for the button when clicked.
Step 4: Serve the Application
To serve the application, run the following command in your terminal:
This command will start a Panel server and automatically reload changes as you edit the files.
The result should look like this:
You'll have to turn on the sound to hear the chime.
Step 4: Develop the Application with Autoreload
When you save your .py, .js or .css file, the Panel server will automatically reload the changes. This feature is called auto reload or hot reload.
Try changing "ipymario-bounce 0.2s" in the mario_button.js file to "ipymario-bounce 2s" and save the file. The Panel server will automatically reload the changes.
Try clicking the button to see the button bounce more slowly.
Conclusion
You've now created a custom MarioButton component using JSComponent in HoloViz Panel. This button features a pixelated Mario icon, plays a chime sound when clicked, and has customizable parameters for gain, duration, size, and animation.