Skip to content

Instantly share code, notes, and snippets.

@gurkanakdeniz
Last active July 6, 2019 00:51
Show Gist options
  • Save gurkanakdeniz/f3ab370b698d788e0014d64dd98f08b7 to your computer and use it in GitHub Desktop.
Save gurkanakdeniz/f3ab370b698d788e0014d64dd98f08b7 to your computer and use it in GitHub Desktop.
socket javascript listener
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" const="text/html;charset=UTF-8" />
<link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="style.css" >
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<title>Socket Example</title>
</head>
<body>
<section>
<div id="change_username">
<input id="username" type="text" />
<button id="send_username" type="button">Change username</button>
</div>
</section>
<section id="chatroom">
<section id="feedback"></section>
</section>
<section id="input_zone">
<input id="message" class="vertical-align" type="text" />
<button id="send_message" class="vertical-align" type="button">Send</button>
</section>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="chat.js"></script>
</body>
</html>
$(function(){
//make connection
var socket = io.connect('http://localhost:3000')
//buttons and inputs
var message = $("#message")
var username = $("#username")
var send_message = $("#send_message")
var send_username = $("#send_username")
var chatroom = $("#chatroom")
var feedback = $("#feedback")
//Emit message
send_message.click(function(){
socket.emit('message', {message : message.val()})
})
//Listen on new_message
socket.on("new_message", (data) => {
feedback.html('');
message.val('');
chatroom.append("<p class='message'>" + data.username + ": " + data.message + "</p>")
})
//Emit a username
send_username.click(function(){
socket.emit('message', {username : username.val()})
})
//Emit typing
message.bind("keypress", () => {
socket.emit('typing')
})
//Listen on typing
socket.on('typing', (data) => {
feedback.html("<p><i>" + data.username + " is typing a message..." + "</i></p>")
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment