Tips on verifying if user x has sent over two messages in the chat and concealing their identity

I have a JavaScript chat application that is causing me some trouble. I recently implemented a feature to display user names on top of messages, and while it works well for the first message, I am struggling to hide the user's name when they send subsequent messages. I attempted to use CSS to solve this issue, but it proved to be too complex as only one user's name would appear at a time. Is there a way to achieve this using JavaScript instead? My goal is to create a chat interface similar to Messenger where:

- If user Bob sends multiple messages, his name should only appear above the first message.

- If user Mark sends a message, his name should only appear on top of his first message, not on subsequent ones from him.

Is there a way to accomplish this using JavaScript? It seems like a difficult task with just CSS alone, so any guidance would be greatly appreciated.

I'm currently using PHP Sessions to retrieve the username in JavaScript, so solutions involving LocalStorage may not be suitable. Ideally, I would prefer avoiding cookies or JavaScript sessions and creating a variable if possible.

https://i.sstatic.net/DH4bb.png

var chat = document.getElementById('chat');
var send = document.getElementById('send');

function SendMessage(who, data) {
  var li = document.createElement('li');
  li.classList.add(who);
  var userName = document.createElement('div');
  userName.classList.add('user');
  userName.textContent = 'Mark';
  li.appendChild(userName);
  var msg = document.createElement('div');
  msg.classList.add('msg');
  var span = document.createElement('span');
  span.textContent = data.message;
  msg.appendChild(span);
  li.appendChild(msg);

  chat.appendChild(li);
}

send.addEventListener('click', function() {
  SendMessage('him', {
    message: 'I love to code'
  });
});
body{
  margin:0;
}

ul {
  margin: 0;
  padding: 20px;
  display: flex;
  flex-direction: column;
  list-style-type: none
}

ul li {
  font-family: Helvetica, Arial, sans-serif;
  display: flex;
  flex-direction: column;
}

ul li .user {
  font-size: 0.6em;
  color: grey;
}

.him { align-self: flex-start; }
.me  { align-self: flex-end; }

.msg {
  padding: 10px;
  border-radius: 30px;
  margin-bottom: 2px;
}

.him .user { text-align: left;  margin-left: 10px; }
.me  .user { text-align: right; margin-right: 10px; }

.him .msg { background: yellow; }
.me  .msg { background: #0084ff; color: #fff; }




.center{
    background-color:black;
    /* width:500px; */
    height:100vh;
    margin:0 auto 0 auto;
    width:100vw;
    overflow: auto;
    
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
   
</head>
<body>
    <div class="center">
    <ul id="chat">
        <li class="him">
          <div class="user">Bob</div>
          <div class="msg">
            <span>Hello World</span>
          </div>
        </li>
        <li class="me">
          <div class="user">Me</div>
          <div class="msg">
            <span>Hello World</span>
          </div>
        </li>
        <li class="him">
          <div class="user">Bob</div>
          <div class="msg">
            <span>How to hide the name after x user sends more than one message</span>
          </div>
        </li>
        <li class="him">
          <div class="user">Bob</div>
          <div class="msg">
            <span>How to hide the name after x user sends more than one message</span>
          </div>
        </li>
      </ul>
      <button id="send" style="float:right;">Send</button>
      </div>

</body>
</html>

Answer №1

If you're looking to determine the sender of the last message, you can use this logic:

if(lastUserName == currentUserName)
   addLI()
else
  addULwithLI();

By following this approach, you'll be able to structure your HTML with ul > li.username elements as shown below:

    <ul  class="him">
      <li class="user">Bob</li>
     <li>
      <div class="msg">
        <span>How to hide the name after x user sends more than one message</span>
      </div>
    </li>
     <li>
      <div class="msg">
        <span>How to hide the name after x user sends more than one message</span>
      </div>
    </li>
     <li>
      <div class="msg">
        <span>How to hide the name after x user sends more than one message</span>
      </div>
    </li>
    </ul>

If the username changes, include both ul li elements; otherwise, just append li.

Edit:

function SendMessage(who, userName, data) {
var lastUser = getLastUser();
if(userName == lastUser) {
  saveLastUser(userName);
  var li = document.createElement('li');
  li.classList.add(who);
  var msg = document.createElement('div');
  msg.classList.add('msg');
  var span = document.createElement('span');
  span.textContent = data.message;
  msg.appendChild(span);
  li.appendChild(msg);
  
  chat.appendChild(li);
 }else{
  var li = document.createElement('li');
  li.classList.add(who);
  var userName = document.createElement('div');
  userName.classList.add('user');
  userName.textContent = 'Mark';
  li.appendChild(userName);
  var msg = document.createElement('div');
  msg.classList.add('msg');
  var span = document.createElement('span');
  span.textContent = data.message;
  msg.appendChild(span);
  li.appendChild(msg);
  saveLastUser()
  chat.appendChild(li);
  }
}
function  getLastUser() {
  // get last user from saved in db.
 return localStorage.getItem('lastUser');
}
function  saveLastUser(username) {
  // save last user from saved in db.
  localStorage.setItem('lastUser',username);
}

Ensure that the JavaScript generates HTML in the specified format for easier integration of li elements within ul threads by the same person.

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

Aligning the Navigation Bar to the Upper Right Corner

I'm attempting to rearrange my Nav Bar to be at the Top Right, with my logo on the Top Left all in one line. Unfortunately, I'm struggling to achieve this and could really use some guidance. As a newcomer to HTML and CSS, I find it challenging to ...

The ckeditor vanishes upon refreshing the div element

I have created two pages named openclosediv.php and content.php. The openclosediv.php page contains a list of records and a button that can show/hide the div, bringing in the content from content.php. However, I am facing an issue where the CKEditor in the ...

Adding click functionality to dynamically generated list items in jQuery and HTML

I'm encountering an issue while trying to assign click events to dynamically added HTML elements in jQuery. Despite extensive research within this community, I find myself more confused than before. Below is the snippet of code causing me trouble: v ...

Vue is currently operating in development mode

I keep receiving this notification each time I visit the site: Vue is currently running in development mode. Remember to switch to production mode when deploying for production. Find more helpful tips at .... I came across a solution from someone suggest ...

The rule 'import/no-cycle' definition could not be located

After removing my npm package along with the package.lock.json file, I proceeded to run 'npm install' and followed up with 'npm update'. However, upon starting my application using 'npm run start', an error occurred. Upon lau ...

In Typescript, if at least one element in an array is not empty, the function should return false without utilizing iterators

My current approach involves receiving a string array and returning false if any of the elements in the array is false. myMethod(attrs: Array<String>) { for (const element of attrs) { if (!element) { return false; } } ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

transferring data from one HTML file to another using a loop with technologies such as HTML,

As a beginner in front end development, I am finding it a bit challenging at the moment. Here's what I have so far: 1 main HTML file (index.html) 1 JavaScript file (something.js) 2nd HTML file (something.html) Main HTML: <!DOCTYPE html> < ...

CSS: Revert INPUT Element Back to Default Width

Although it may seem impossible, I am still going to ask the question. Suppose I have the following HTML: <div style="width: 500px;"> <input class="full" /> </div> And the corresponding CSS: input { width: 100%; } .full { ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...

Node.js making an API request

I am encountering an issue with the following code snippet: const req = require("request"); const apiReq = req("http://example.com/car/items.json", (err, res, body) => { if (!err && res.statusCode === 200) { return JSON.parse(body); } } ...

Implementing Angular CDK for a dynamic drag-and-drop list featuring both parent and child elements

I'm currently working on setting up a drag and drop list within Angular using the Angular CDK library. My goal is to create a list that includes both parent and child elements, with the ability to drag and drop both parent items as well as their respe ...

Angular: The function t(...) does not support success - TypeError

My code is generating the error TypeError: t(...).success is not a function. I have tried searching for a solution but haven't been able to figure out why this error is happening in my specific case. Here is a snippet of my JS code. Can anyone point ...

The Node.js application that uses Express and connects to a MSSQL database is reporting that the database

One of my other applications utilizes express and routes, but for this new app I wanted to simplify it. Despite being confident in the correctness of the connection string, I encountered an issue. script.getQuestions(connection); script.getQuestions = fu ...

Generating div elements dynamically and applying styles

Generating a div dynamically and adding style to it var newDiv = document.createElement('div'); newDiv.setAttribute("id","dynamic-div"); document.body.appendChild(newDiv); // Simulating dynamic ajax content loading $(document).ready(function () ...

Terminate the execution of the process.exec function

Currently, I have a function in my code that is responsible for executing a specific process. Here's how it looks: static async runTest() { await process.exec(`start ${currentDir}/forward.py`); } runTest(); Here's the thing – once this Python ...

Modifying the value of a variable causes a ripple effect on the value of another variable that had been linked to it

After running the code below, I am receiving values from MongoDB in the 'docs' variable: collection.find({"Stories._id":ObjectID(storyId)}, {"Stories.$":1}, function (e, docs) { var results = docs; results[0].Stories = []; } I ...

Erase the dynamically loaded page using ajax and conceal the div

Currently, I am utilizing the .on() method with jQuery to display a specific div, and also using .load() to fetch a particular div from a web page hosted on my server. My query is how can I close this div when clicking outside of it, along with removing i ...

How to position an image on the left side using AngularJS in an HTML

In the image, you can see rows. This is the code for the view: <div layout="row" layout-align="space-around center" > <product-image-thumbnail layout="row" layout-align="left center" src="vm.callFunction(field)" setter="vm.callFunction(v ...

Uncovering Inline Styles Infused with Javascript for Effective Debugging of Javascript Code

SITUATION: I have recently inherited a website from the previous developer who has scattered important functions across numerous lengthy JS files. I am struggling to track down the source of an inline CSS style within the JS or identify which function is d ...