-
-
Save littlebookboy/e221f1aff25e4d91db6371a86468f3ff to your computer and use it in GitHub Desktop.
Example vanilla JS WebSocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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