My teacher told us that we can save the names of users (asking the user to write his nickname in a prompt) using "localstorage" and array, because he wants that the names are saved even if the page is reloaded (sorry for my broken english, english is not my first language and i am also new in javascript) :
html:
<!doctype html>
<html>
<head>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function() {
var socket=io();
var nick = prompt("Cual es tu nombre");
socket.emit('nombre', nick);
$("form").submit(function(e){
e.preventDefault();
socket.emit('chat message', $("#m").val());
$("#m").val('');
return false;
});
socket.on('chat message',function(msg){
$("#messages").append($("<li>").text(msg));
});
});
Js:
</script>
</body>
</html>
var app=require('express')();
var http=require('http').Server(app);
var io=require("socket.io")(http);
var puerto=8000;
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
});
io.on('connection',function(socket){
socket.on('nombre', (username) => {
socket.username = username;
console.log('Usuario' + socket.username + 'se conecto')
});
//usamos un callback para notificar que una conexion
console.log('usuario conectado'+socket.username);
socket.on('disconnect',function(){
console.log("Usuario se desconecto");
});
socket.on('chat message',function(msg){
console.log(socket.username + " dijo: ", msg);
io.emit('chat message',socket.username + " dijo: "+msg);
});
});
http.listen(puerto,function(){
console.log("Escuchando puerto " +puerto);
});
You can use localStorage to save user nickname and use this data to check user nickname has already or not.
$(function () {
var NICK_NAME_KEY = 'nickName';
var socket = io();
var nick = localStorage.getItem(NICK_NAME_KEY); // first of all, try to get last nickname from localStorage
if (!nick) { // if do not have nickname in localStorage,
// this mean this is the first time user enters your system
nick = prompt("Cual es tu nombre"); // ask user nickname
localStorage.setItem(NICK_NAME_KEY, nick); // save user nickname to localStorage,
//if user reload page, we will have nickname in localStorage, the system will not ask their nickname again.
} else {
// nickname has already
}
socket.emit('nombre', nick);
$("form").submit(function (e) {
e.preventDefault();
socket.emit('chat message', $("#m").val());
$("#m").val('');
return false;
});
socket.on('chat message', function (msg) {
$("#messages").append($("<li>").text(msg));
});
// create a logout `button`, when user click the button, just remove their data (nicknam) and reload page
$('#logout').on('click', function() {
localStorage.removeItem(NICK_NAME_KEY);
location.reload();
})
});
You can literally do this
localStorage.set('userName', NAME_HERE);
so in your case
socket.on('nombre', (username) => {
socket.username = username;
localStorage.set('Usuario', socket.username);
});
Related
I am developing a simple chat app using javascript and socket.io with node.js
Everything works well, except when chat messages are appended when a chat message is received, the list of chat messages grows but stays at the top instead of scrolling to the bottom to show the last message that arrived.
I have tried all suggestions but the list keeps appending the messages but stays on the top showing the oldest message first and the new ones are not shown unless I manually scroll the list with the mouse
Your help will be greatly appreciated.
Thank you
here is the code:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
and here is the server code run with node.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log('about to send:'+__dirname + '/index.html');
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I have a chat app that uses this jQuery code to smoothly scroll to the bottom of the document. The animation takes 800 milliseconds.
// scroll to bottom of display
$('html, body').animate({scrollTop:$(document).height()}, 800);
Docs for jQuery.animate() and Element.scrollTop.
use scrollTop to go after add new one
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
var ul= document.getElementById("messages");
ul.scrollTop = ul.scrollHeight;
});
});
</script>
I have this simple chat room here:
app.js
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const fs = require('fs');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
var messages;
fs.readFile('log.txt', 'utf8', function(err, data) {
messages = data.split('|/');
for (i = 0; i < messages.length; i++) {
socket.emit('message', messages[i]);
}
if (err) throw err;
})
socket.on('message', function(data) {
fs.appendFile('log.txt',
'<span class="seen">' + data.name + ': ' + data.msg + '</span>' + '|/',
function(err) {
if (err) throw err;
})
socket.broadcast.emit('message', data);
})
})
http.listen(2099, function(){
console.log('litening on :2099');
});
index.HTML
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>chat</title>
<style>
body {
font-family: sans-serif;
font-size: 18px;
background: #404040;
}
input[type=text],[type=submit] {
font-size: 18px;
}
#chatList {
list-style: none;
margin: 0;
padding: 0;
}
#inputContainer {
position: fixed;
bottom: 0;
width: 100%;
margin: 10px;
}
#input {
width: calc(90% - 40px);
padding: 10px 20px;
border: 1px solid white;
border-radius: 10px;
margin-right: -3px;
display: inline-block;
color: white;
background: #404040;
}
#submit {
border: 1px white solid;
border-radius: 10px;
padding: 11px 2.2%;
color: white;
background-color: #404040;
}
.msg {
margin: 0 12px 0px 12px;
padding: 12px;
border-bottom: 1px solid gray;
color: white;
}
.income {
color: crimson;
}
.sender {
color: cyan;
}
</style>
</head>
</head>
<body>
<div id='chat'>
<ul id='chatList'>
</ul>
</div>
<div id='inputContainer'>
<input type="text" id='input' placeholder="Type a message..." autocomplete="off">
<input type="submit" id='submit' value="Send" onclick="send()">
</div>
</form>
<script src='/socket.io/socket.io.js'></script>
<script>
document.getElementById('input').value = '';
var socket = io();
document.addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
send();
}
})
function send() {
value = document.getElementById('input').value;
if (value != '') {
socket.emit('message', {msg: value, name: username})
var list = document.getElementById('chatList');
var msg = document.createElement('li');
msg.className = 'msg';
msg.innerHTML = '<span class="sender">' + username + '</span>' + ': ' + value;
list.appendChild(msg);
document.getElementById('input').value = '';
}
}
socket.on('message', function(data) {
var list = document.getElementById('chatList');
var msg = document.createElement('li');
msg.className = 'msg';
msg.innerHTML = data;
list.appendChild(msg);
})
document.getElementById('input').value = '';
var username = prompt('Choose a username:');
if (username == '') {
username = 'mysteryman' + Math.floor(Math.random() * 100);
}
</script>
</body>
</html>
So this function:
fs.readFile('log.txt', 'utf8', function(err, data) {
messages = data.split('|/');
for (i = 0; i < messages.length; i++) {
socket.emit('messages', messages[i]);
}
if (err) throw err;
})
Were suppose to read data from log.txt and send it as events for the clients to load in old messages. Its working okay but the client side is not receiving any events even though this loop is running and sending events.
I have tried making sure that all events are loaded before sending the data.
Any help would be greatly appreciated!!!
Your typo mistake, you emit messages event on server side, but listen to message (without s) event on client side.
My guess is when the server fires the socket.emit('message'..., the socket in the client has not been registered yet the socket.on('message'...
I have managed to write the following code. The idea is to be able to get a pop up asking how much ETH I want to send.
But I am not able to get the pop-up. I have spent hours to fix this and not able to reach a conclusion.
I am able to get the popup sometimes but only when I refresh the page.
<!doctype html>
<html>
<head>
<title>MetaMask</title>
<style>
input[type=number], select {
width: 50%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.tip-button {
width: 304px;
height: 79px;
background-size: 100%;
background-image: url('https://github.com/MetaMask/TipButton/raw/master/images/1_pay_mm_over.png');
cursor: pointer;
}
.tip-button:hover {
background-image: url('https://github.com/MetaMask/TipButton/raw/master/images/1_pay_mm_over.png');
}
.tip-button:active {
background-image: url('https://github.com/MetaMask/TipButton/raw/master/images/1_pay_mm_off.png');
}
</style>
</head>
<body>
<h3>To Proceed please click the METAMASK LOGO below.</h3>
<h3>A popup will appear to ask you the ETH amount</h3>
<div class="tip-button"></div>
<div class="message"></div>
</body>
<script>
var MY_ADDRESS = '0x7266D19108705D60066f5d0c29f60893A7B1fE14'
var tipButton = document.querySelector('.tip-button')
tipButton.addEventListener('click', function() {
if (typeof web3 === 'undefined') {
return renderMessage('<div>Looks like you dont have <a href=https://metamask.io>MetaMask</a> to use this feature. <a href=https://metamask.io>https://metamask.io</a></div>')
}
var numSubmit = prompt("Please enter the ETH amount.");
if(isNaN(numSubmit)) {
numSubmit = prompt("A number is required.");
numSubmit = +numSubmit;
}
else {
numSubmit = +numSubmit;
}
var user_address = web3.eth.accounts[0]
web3.eth.sendTransaction({
to: MY_ADDRESS,
from: user_address,
value: web3.toWei(numSubmit, 'ether'),
gas: 232575,
gasPrice: 4000000000,
}, function (err, transactionHash) {
if (err) return renderMessage('There was a problem! Please reload the Page again.')
// If you get a transactionHash, you can assume it was sent,
// or if you want to guarantee it was received, you can poll
// for that transaction to be mined first.
renderMessage('Thank You')
})
})
function renderMessage (message) {
var messageEl = document.querySelector('.message')
messageEl.innerHTML = message
}
</script>
</html>
Thank you!
I'm new with Node.js and Socket.IO and I can't seem to figure out why I keep getting "undefined", I'm trying to get a username in front of the message which it does, but I cant seem to get rid of that nasty undefined.
Here is my index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
io.emit('chat message','User Connected');
socket.on('disconnect', function(){
io.emit('chat message','User Disconnected');
console.log('user disconnected');
});
});
http.listen(13280, function(){
console.log('listening on *:13280');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg,username){
io.emit('chat message',username + msg);
});
});
and here my index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
.name {margin-bottom: 40px;}
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var name = prompt("Choose a username","username");
var halveusername = "[" + name;
var username = halveusername + "] ";
var socket = io();
$('form').submit(function(){
socket.emit('chat message',username + $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
You are probably better off sending a json object as the message if it contains multiple values - it gives you more flexibility and will fix your error in any case.
Try this
in index.js
io.on('connection', function(socket){
socket.on('chat message', function(message){
io.emit('chat message', message);
});
});
and in index.html
$('form').submit(function(){
var message = {
username: username,
text: $('#m').val()
};
socket.emit('chat message', message);
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg.username + msg.text));
});
I have followed a tutorial for socket.io chat:
https://www.youtube.com/watch?v=pNKNYLv2BpQ
In the tutorial video it works fine however mine does not work at all. The messages do not seem to be sent or received by either the server or the client
This is my app.js run on the server side with node
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
This is my index.html client
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat
{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($) {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat $('#chat');
$messageForm.submit(function(e) {
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function(data) {
$chat.append(data + "<br/>");
});
});
</script>
I suppose it is a simple error that I have overlooked but I'm stumped at the moment, any ideas ??? Also if you require additional information please say so :)
create one index.html file
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
For more information click here