Skip to content

Instantly share code, notes, and snippets.

@alecordev
Created June 7, 2017 11:35
Show Gist options
  • Save alecordev/8699876bbb0d9c9169bc18ecf43af764 to your computer and use it in GitHub Desktop.
Save alecordev/8699876bbb0d9c9169bc18ecf43af764 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>
@daslicht
Copy link

how about a vanilla server side ?

@vzakharov
Copy link

how about a vanilla server side ?

Yep, that would be much appreciated 🙂

@JosephVoid
Copy link

how about a vanilla server side ?

There is no vanilla JS for server side, its just node.

@daslicht
Copy link

daslicht commented Oct 11, 2023

how about a vanilla server side ?

There is no vanilla JS for server side, its just node.

That obvious, by vanilla I mean't without a framework

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment