Help with updating username color in a chatroom

Please note I am just attempting to use this to learn and it is no big deal if I don’t solve it. I do not intend to actually ever use this for anything it is just something I attempted to build while messing around with AI. If you can spot the issues easily then I would appreciate the help but if it’s too time consuming please don’t worry about it.


Question:



I’m having this issue in this “chatroom” I used AI to help me build.
When a user in the chatroom changes their username and sends a message, it displays a notification in the chat that they changed their name.

(1 changed name to 2.)

However, if they change their username, and change the color of their username before sending a message, it shows
" (1(new color) changed name to 2(new color))"
It should be “(1(old color) changed name to 2(new color)).
(1 should stay the old color it was before.)

The “changed name to” part is not considered a user message, but a system message, so remains the default white, instead of being the user’s message color or username color.

If the user just changes the color of their username, while not changing their username itself, there should be no notification and it should just display their message as its color and their username as it’s new username color.

(2(newcolor): message)

I’m not sure what all is causing this to happen as I built it piece by piece without a plan to start with. My suspicion is that since they have to send a message in order for the chatroom to see that they changed their username, it’s technically changing the color of their old username first, and then changing their name? I don’t know if it’s instantly changing their username color as soon as they choose it?

I’ve tried a few different alterations but to no avail,

here is a brief list of some of the things I've tried.

Changing how it updates the usernameColor variable when a new username is set.

Updating the usernameColor variable only after we have used the oldUsernameColor to format the old username.

Directly retrieving the color from the usernameColorInput element when formatting the old username. Instead of relying on the usernameColor variable.

Updating the oldUsernameColor variable after checking if the username has changed

introducing a separate variable to store the new username color before updating the usernameColor variable.

introducing a temporary variable to store the old username color and only update the usernameColor when a message is sent.

Modifying the formatUsername function to conditionally include the color only if a message is sent and after constructing the part of the message containing the old username.

Modifying the formatUsername function to include both the old and new colors.

Entire code
<!DOCTYPE html>
<html>
<head>
    <title>My Chatroom</title>
    <style>
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            background-color: #000000;
            font-family: Arial, sans-serif;
        }
        #chatbox-container {
            text-align: center;
        }
        #chatbox {
            width: 600px;
            height: 400px;
            border: 1px solid #ccc;
            padding: 10px;
            overflow-y: scroll;
            margin: 0 auto;
            background-color: #333333;
            color: #ffffff;
        }
        #input {
            width: 600px;
            margin: 0 auto;
        }
        #usernameColorInput {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div id="container">
        <h1>My Chatroom</h1>
        <div id="chatbox-container">
            <div id="chatbox"></div>
            <input type="text" id="usernameInput" placeholder="Enter your username..." />
            <input type="color" id="usernameColorInput" />
            <br>
            <input type="text" id="messageInput" placeholder="Type your message..." />
            <input type="color" id="messageColorInput" />
            <br>
            <button id="sendButton">Send</button>
            <button id="clearChatButton">Clear Chat</button>
        </div>
    </div>

    <script>
        var username = '';
        var usernameColor = '#ffffff';
        var messageColor = '#ffffff';

        function sendMessage() {
            var messageInput = document.getElementById('messageInput');
            var message = messageInput.value.trim();

            if (message !== '') {
                var chatbox = document.getElementById('chatbox');
                var messageElement = document.createElement('p');
                var currentDate = new Date().toLocaleDateString();
                var currentTime = getCurrentTime(); // Get current time
                var newUsername = document.getElementById('usernameInput').value.trim();
                var oldUsername = username;
                var oldUsernameColor = usernameColor;

                if (newUsername !== oldUsername) {
                    if (oldUsername !== '') {
                        messageElement.innerHTML = '[' + currentDate + ' ' + currentTime + '] <span style="color: ' + oldUsernameColor + '">' + oldUsername + '</span> changed name to <span style="color: ' + usernameColor + '">' + newUsername + '</span>';
                    }
                    username = newUsername;
                }

                if (username !== '') {
                    messageElement.innerHTML += '<br>[' + currentDate + ' ' + currentTime + '] <span style="color: ' + usernameColor + '">' + username + '</span>: <span style="color: ' + messageColor + '">' + message + '</span>';
                }

                chatbox.appendChild(messageElement);

                messageInput.value = '';
                messageInput.focus();

                // Store the message in local storage with colors
                var messages = localStorage.getItem('chatMessages') ? JSON.parse(localStorage.getItem('chatMessages')) : [];
                messages.push('[' + currentDate + ' ' + currentTime + '] ' + formatUsername(username, usernameColor) + ': ' + formatMessage(message, messageColor));
                localStorage.setItem('chatMessages', JSON.stringify(messages));
            }
        }

        function formatUsername(username, color) {
            return '<span style="color: ' + color + '">' + username + '</span>';
        }

        function formatMessage(message, color) {
            return '<span style="color: ' + color + '">' + message + '</span>';
        }

        function getCurrentTime() {
            var now = new Date();
            var hours = now.getHours().toString().padStart(2, '0');
            var minutes = now.getMinutes().toString().padStart(2, '0');
            var seconds = now.getSeconds().toString().padStart(2, '0');
            var time = hours + ':' + minutes + ':' + seconds;
            return time;
        }

        function loadMessages() {
            var chatbox = document.getElementById('chatbox');
            chatbox.innerHTML = ''; // Clear the chatbox before loading messages
            var messages = localStorage.getItem('chatMessages');
            if (messages) {
                messages = JSON.parse(messages);
                messages.forEach(function (message) {
                    var messageElement = document.createElement('p');
                    messageElement.innerHTML = message;
                    chatbox.appendChild(messageElement);
                });
            }
        }

        function clearChat() {
            var chatbox = document.getElementById('chatbox');
            chatbox.innerHTML = ''; // Clear the chatbox by setting its innerHTML to an empty string
            localStorage.removeItem('chatMessages'); // Remove chat messages from local storage
        }

        document.getElementById('usernameColorInput').addEventListener('input', function (event) {
            usernameColor = event.target.value;
        });

        document.getElementById('messageColorInput').addEventListener('input', function (event) {
            messageColor = event.target.value;
        });

        document.getElementById('sendButton').addEventListener('click', sendMessage);

        document.getElementById('clearChatButton').addEventListener('click', clearChat);

        loadMessages();
    </script>
</body>
</html>

Repl link: Repl or Playcode.io

2 Likes

Chatgpt solved this for me.

It said
Here are the key changes I made to the code:

  1. Initialization of oldUsernameColor: I initialized the variable oldUsernameColor outside the sendMessage function. This ensures that it retains its value across function calls and is accessible throughout the script.
  2. Updating oldUsernameColor: I updated the value of oldUsernameColor whenever the username changes. This is done inside the condition where we check if the new username is different from the old one. By updating oldUsernameColor at this point, we ensure that it always stores the color of the username before it gets updated with a new color.

These changes ensure that oldUsernameColor correctly retains the old username color and persists it in the update username message.

// Initialized oldUsernameColor outside the sendMessage function
var oldUsernameColor = '#ffffff'; 

function sendMessage() {
    // Other code remains the same...

    if (newUsername !== oldUsername) {
        // Moved the declaration of oldUsernameColor inside this block
        var oldUsernameColor = usernameColor; // Store the current username color
        if (oldUsername !== '') {
            // Used oldUsernameColor instead of usernameColor here
            messageElement.innerHTML = '[' + currentDate + ' ' + currentTime + '] <span style="color: ' + oldUsernameColor + '">' + oldUsername + '</span> changed name to <span style="color: ' + usernameColor + '">' + newUsername + '</span>';
        }
        username = newUsername;
    }

    // Other code remains the same...
}

In summary, I moved the declaration of oldUsernameColor inside the block where we check if the new username is different from the old one. This ensures that oldUsernameColor is only updated when necessary. Then, I used oldUsernameColor instead of usernameColor in the update username message to ensure that it retains the correct color.

The issue with the original code was related to how the oldUsernameColor variable was being managed.

  1. Scope of oldUsernameColor: Originally, oldUsernameColor was declared within the sendMessage function. This means that every time sendMessage was called, a new instance of oldUsernameColor was created and initialized to '#ffffff'. This prevented the variable from retaining its value across different function calls.
  2. Timing of Updating oldUsernameColor: In the original code, oldUsernameColor was being updated after the username variable was updated with the new username. This meant that oldUsernameColor was always updated to the new username color before it could be used to display the previous username color in the update username message.

By initializing oldUsernameColor outside the sendMessage function and updating it at the appropriate time (before updating username), we ensure that it correctly stores the old username color and retains it for use in the update username message. This ensures that the message displays the correct old username color.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.