Skip to content

Instantly share code, notes, and snippets.

@littlebookboy
Forked from alecordev/index.html
Created May 10, 2022 08:38
Show Gist options
  • Save littlebookboy/e221f1aff25e4d91db6371a86468f3ff to your computer and use it in GitHub Desktop.
Save littlebookboy/e221f1aff25e4d91db6371a86468f3ff to your computer and use it in GitHub Desktop.
Example vanilla JS WebSocket
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// use vanilla JS because why not
window.addEventListener("load", function() {
// create websocket instance
var mySocket = new WebSocket("ws://localhost:8080/ws");
// add event listener reacting when message is received
mySocket.onmessage = function (event) {
var output = document.getElementById("output");
// put text into our output div
output.textContent = event.data;
};
var form = document.getElementsByClassName("foo");
var input = document.getElementById("input");
form[0].addEventListener("submit", function (e) {
// on forms submission send input to our server
input_text = input.value;
mySocket.send(input_text);
e.preventDefault()
})
});
</script>
<style>
/* just some super basic css to make things bit more readable */
div {
margin: 10em;
}
form {
margin: 10em;
}
</style>
</head>
<body>
<form class="foo">
<input id="input"></input>
<input type="submit"></input>
</form>
<div id="output"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment