Hey andfanilo,
this is great thank you! I have frankensteineād that code and the JS-Python communication works. But unfortunately I realized that the page seems to refresh now everytime I use the html slider Do you know of a way to fix that?
Python code:
import streamlit as st
import streamlit.components.v1 as components
# Declare the custom component
mycomponent = components.declare_component(
"mycomponent",
path="./mycomponent"
)
# Initial slider value (50 in this example)
slider_value = mycomponent(my_input_value=50)
# Display the slider value in Streamlit
st.write("Slider Value:", slider_value)
HTML/JS code:
<html>
<body>
<!-- Set up your HTML here -->
<input type="range" id="brightnessSlider" min="0" max="100" step= "1" value="50" onchange="updateColor()">
<div id="colorBox" style="width: 200px; height: 50px; background-color: rgb(0,0,0);"></div>
<script>
// ----------------------------------------------------
// Just copy/paste these functions as-is:
function sendMessageToStreamlitClient(type, data) {
var outData = Object.assign({
isStreamlitMessage: true,
type: type,
}, data);
window.parent.postMessage(outData, "*");
}
function init() {
sendMessageToStreamlitClient("streamlit:componentReady", { apiVersion: 1 });
}
function setFrameHeight(height) {
sendMessageToStreamlitClient("streamlit:setFrameHeight", { height: height });
}
// The `data` argument can be any JSON-serializable value.
function sendDataToPython(data) {
sendMessageToStreamlitClient("streamlit:setComponentValue", data);
}
// ----------------------------------------------------
// Now modify this part of the code to fit your needs:
var mySlider = document.getElementById("brightnessSlider");
function updateColor() {{
var sliderValue = document.getElementById('brightnessSlider').value;
var grayValue = 255 - (sliderValue * 2.55);
document.getElementById('colorBox').style.backgroundColor = 'rgb(' + grayValue + ',' + grayValue + ',' + grayValue + ')';
}}
// Call the function initially to set the initial color
updateColor();
// Function to send slider value to Streamlit
function onSliderChange() {
sendDataToPython({
value: mySlider.value,
dataType: "json",
});
}
function onDataFromPython(event) {
if (event.data.type !== "streamlit:render") return;
// Access data sent from the Streamlit app here, if needed
}
mySlider.addEventListener("input", onSliderChange);
// Hook things up!
window.addEventListener("message", onDataFromPython);
init();
// Hack to autoset the iframe height.
window.addEventListener("load", function () {
window.setTimeout(function () {
setFrameHeight(document.documentElement.clientHeight);
}, 0);
});
// Optionally, if the automatic height computation fails you, give this component a height manually
// by commenting out below:
//setFrameHeight(200);
</script>
</body>
</html>