How to Build a Simple Chat Application Using jQuery's text() Method for Dynamic Messaging

← Prev

A simple chat application using jQuery's text() method enables dynamic messaging by efficiently updating text-based content without modifying HTML structure. This approach is ideal for lightweight chat systems where instant user input is reflected in a conversation window. By leveraging jQuery's text() function, developers can ensure cleaner code and improved accessibility while maintaining a smooth, real-time chatting experience.

Example:

The Markup
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Chat App using jQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  
  <style>
    * { font-family: 'Segoe UI' }
    #chatBox {
      width: 300px;
      height: 250px;
      border: 1px solid #ccc;
      padding: 10px;
      overflow-y: auto;
      background-color: #f9f9f9;
    }
    #typingStatus {
      color: gray;
      font-style: italic;
    }
    .message {
      padding: 5px;
      border-radius: 5px;
      margin: 5px 0;
    }
    .user-msg {
      background-color: #d1e7dd;
    }
    .system-msg {
      background-color: #f8d7da;
    }
  </style>
</head>
<body>
  <div id="chatBox">
    <p><strong>Chat:</strong></p>
  </div>

  <p id="typingStatus"></p>
  <input type="text" id="messageInput" placeholder="Type a message..." />
  <button id="sendButton">Send</button>
</body>
The Script
<script>
    $(document).ready(function () {
        function getTimestamp() {
            let now = new Date();
            return now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }

        // Show "User is typing..." while typing.
        $('#messageInput').on('input', function () {
            let msgText = $(this).val().trim();
            if (msgText) {
                $('#typingStatus').text('User is typing...');
            } else {
                $('#typingStatus').text('');
            }
        });

        // Send message and update chat box.
        $('#sendButton').on('click', function () {
            let msgText = $('#messageInput').val().trim();
            if (msgText) {
                let formattedMsg = formatEmoji(msgText);
                let time = getTimestamp();
                $('#chatBox').append(`<p class="message user-msg"><strong>You:</strong> ${formattedMsg} <small>[${time}]</small></p>`);
                $('#messageInput').val(''); // Clear input field.
                $('#typingStatus').text(''); // Remove typing indicator.

                // Simulate system reply after 1000 miliseconds (or 1 second).
                setTimeout(function () {
                    $('#chatBox').append(`<p class="message system-msg"><strong>System:</strong> I am good. How are you? <small>[${getTimestamp()}]</small></p>`);
                }, 1000);
            }
        });

        function formatEmoji(text) {
            return text.replace(":)", "😊")
                .replace(":(", "☹️")
                .replace("<3", "❤️");
        }
    });
</script>
</html>
Try it

That's it. In this simple chat application, jQuery’s text() method efficiently updates the chat display with user input while ensuring clean text rendering. The setTimeout() function introduces a slight delay to simulate real-time interactions, making the system feel more dynamic.

← Previous