Storing the usernames of users through local storage is essential for data preservation

My instructor mentioned a unique way to store user names using "localstorage" and arrays in JavaScript. This method ensures that the names are saved even if the page is reloaded. Here is the code snippet for achieving this functionality:

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("Enter your name");
    socket.emit('name', 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 port=8000;

app.get('/',function(req,res){
    res.sendFile(__dirname+'/index.html');
});

io.on('connection',function(socket){
    socket.on('name', (username) =>  {
        socket.username = username;
        console.log('User ' + socket.username + ' has connected')
    });
    //using a callback to notify a connection
    console.log('user connected'+socket.username);
    socket.on('disconnect',function(){
        console.log("User has disconnected");
    });

    socket.on('chat message',function(msg){
        console.log(socket.username + " said: ", msg);
        io.emit('chat message',socket.username + " said: "+msg);
    });
});

http.listen(port,function(){
    console.log("Listening on port " +port);
});

Answer №1

If you want to store a user's nickname for future use, you can utilize the localStorage feature. This way, you can easily check if the user already has a stored nickname.

$(function () {
  var NICK_NAME_KEY = 'nickName';
  var socket = io();
  var nick = localStorage.getItem(NICK_NAME_KEY);
  if (!nick) {
    nick = prompt("What is your name");
    localStorage.setItem(NICK_NAME_KEY, nick);
  } else {
    // User's nickname already exists
  }
  socket.emit('name', 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 that removes the stored nickname and reloads the page
  $('#logout').on('click', function() {
    localStorage.removeItem(NICK_NAME_KEY);
    location.reload();
  })
});

Answer №2

This can easily be accomplished.

localStorage.update('user', USER_NAME);

Therefore, in your situation

socket.on('name', (user) =>  {
    socket.user = user;
    localStorage.update('User', socket.user);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhancing User Experience with JavaScript Double Click Feature in Three.js

Currently, I have implemented a double click function that allows the user to double click on a car model, displaying which objects have been intersected such as wipers, grille, and tires. These intersections are listed along with the number of items the d ...

What might be causing certain ajax buttons to malfunction?

There are 5 buttons displayed here and they are all functioning correctly. <button type="submit" id="submit_button1">Img1</button> <button type="submit" id="submit_button2">Img2</button> <button type="submit" id="submit_button3" ...

Load a 3D object or model using three.js and then make modifications to its individual components

Seeking advice on displaying and manipulating a 3D model of a robot arm in a browser. How can I load the model into three.js to manipulate all the sub-parts of the robot arm? Using Inventor, I have an assembly of a rotary motor and a shaft exported as an ...

Guide for displaying information as a grid or table format using Angular 4

I am tasked with handling data from an external microservice that is not always in a standard format. The data is dynamic and can include table data, along with metadata information above the grid. My challenge is to render or identify the table data, disp ...

Set an attribute without replacing any existing class attributes

I have developed a script that updates the class attribute of the body element on my website when an option is selected from a dropdown menu. However, I am facing an issue where it overrides the existing dark mode attribute. The purpose of this script is ...

Unable to change the value of Apexcharts components

Utilizing the Vue.js framework along with the Apexchart library, I have been able to create scatterplots for my data. By making use of Axios, I can successfully transmit my data and monitor it using console.log(). With the help of Apexcharts property updat ...

Encountering a 404 error while trying to delete using jQuery

I have been attempting to execute a 'DELETE' call on an API, but so far I have had no success. Despite being able to access the URI and view the JSON data, my DELETE request does not work. Interestingly, other web services are able to perform thi ...

Show the result as "Content-Type: image/jpeg" on the webpage

I have a URL for an API request that automatically downloads and saves a QR code image from the browser. The Content-Type of the URL is application/jpeg, and its format looks like this: application(websiteURL)/egs?cmd=gen_qrcode&customer_id=123&n ...

How to obtain the height of the parent screen using an iframe

Imagine a scenario where a div contains an image that is set to perfectly fit the height of the screen. This setup works flawlessly, with one exception - when placed within an iframe, the height of the div adjusts to match the content's height rather ...

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

Retrieving Information from an API with Custom Headers in React Native

I have an API that necessitates specific headers for access. Without these headers, a browser displays the following error: Code: 4101 Message: Header X-Candy-Platform is required However, when the headers are provided, the API returns a json response. ...

"Encountering difficulties while trying to modify the QuillNoSSRWrapper value within a Reactjs

Currently, I am working on a project involving ReactJS and I have opted to use the Next.js framework. As of now, I am focused on implementing the "update module" (blog update) functionality with the editor component called QuillNoSSRWrapper. The issue I ...

Node.js is having trouble locating the JSON file for Ajax requests

Currently, I've developed a fun little game using the p5.js library and wanted to integrate a Leaderboard feature that pulls data from a JSON file acting as a database to store Usernames and scores. To achieve this, I've utilized a Node.js server ...

Issues with AngularJS <a> tag hyperlinks not functioning as expected

After performing a search, I have an array of objects that needs to be displayed on the template using ng-repeat. The issue arises when constructing the URL for each item in the array – although the ng-href and href attributes are correct, clicking on th ...

Leveraging JavaScript to create a horizontal divider

Just a quick question - how can I create a horizontal line in Javascript that has the same customization options as the HTML <hr> tag? I need to be able to specify the color and thickness of the line. I am working on a website where I have to includ ...

Guide to adding a JS file from npm package to a new page in Nuxt.js

I am facing an issue where I have multiple npm packages containing client-side scripts that I need to include in different pages of my Nuxt.js project. I attempted to achieve this by using the following method: <script> export default { head: { ...

Prevent a sliding panel from responding if there is no input text by incorporating jQuery

I have a straightforward example of user input and a button that reveals "Hello World" when clicked: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

ASP.Net - Unexpected JSON Format Error

As I work on my ASP.Net web application, I am encountering an issue with binding data from a database to a Google Combo chart via a Web Service class. While I can successfully bind the data to a grid view, attempting to bind it to the chart results in the ...