In this this tutorial, https://www.w3schools.com/nodejs/nodejs_raspberrypi_webserver_websocket.asp , It has even handler that works off of an HTML checkbox. I would like to do the exact same thing, but with a button, so that I can temporarily unlock a door. As long as the button is pressed by the mouse, the door is unlocked. Once the mouse button is released, the door locks. The default position is locked. Below is the code from the link above:
<!DOCTYPE html>
<html>
<body>
<h1>Control LED light</h1>
<p><input type="checkbox" id="light"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script> <!-- include socket.io client side script -->
<script>
var socket = io(); //load socket.io-client and connect to the host that serves the page
window.addEventListener("load", function(){ //when page loads
var lightbox = document.getElementById("light");
lightbox.addEventListener("change", function() { //add event listener for when checkbox changes
socket.emit("light", Number(this.checked)); //send button status to server (as 1 or 0)
});
});
socket.on('light', function (data) { //get button status from client
document.getElementById("light").checked = data; //change checkbox according to push button on Raspberry Pi
socket.emit("light", data); //send push button status to back to server
});
</script>
</body>
</html>
Essentially, I would like to use
<input type="button" id="light" value="light">
instead of
<input type="checkbox" id="light">
Thank you!
2
Answers
To get the code to work exactly the way I wanted it, I did the following;
And I added the following JavaScript:
@mplungjan Thanks again!
Use a data attribute on a button