Free Chat Box for Website Code

Free Chat Box for Website Code

Here is example code of Chat box.
Head Section:

  <style>
    body {
      font-family: Arial, sans-serif;
    }
    .container {
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      border: 1px solid #ccc;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    .messages {
      height: 300px;
      overflow-y: scroll;
      border: 1px solid #ccc;
      padding: 10px;
    }
    .message {
      margin-bottom: 10px;
      padding: 5px;
      background-color: #f2f2f2;
      border-radius: 5px;
      color: black;
    }
    .admin-message {
      text-align: right;
      background-color: #c9e6ff;
    }
    .user-message {
      text-align: left;
      background-color: #fff;
    }
    .input-container {
      display: flex;
    }
    .input-container input {
      flex: 1;
      padding: 10px;
    }
    .input-container button {
      padding: 10px;
    }
  </style>


Body Section:

  <div class="container">
    <div class="messages" id="message-container"></div>
    <div class="input-container">
      <input type="text" id="message-input" placeholder="Type your message...">
      <button id="send-button">Send</button>
    </div>
  </div>

  <script>
    const messageContainer = document.getElementById('message-container');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');

    // Generate a unique user ID
    const userId = Math.random().toString(36).substr(2, 9);
    const adminName = 'Online Source'; // Customize the admin name
    const userName = 'User'; // Customize the user name

    const API_BASE_URL = 'http://localhost:3000'; // Update with your API server URL

    function sendMessage(message, sender) {
      const data = {
        sender: sender,
        message: message,
      };

      // Make an API call to send the message to the server
      fetch(`${API_BASE_URL}/messages`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })
        .then((response) => response.json())
        .then(() => {
          appendMessage(message, sender);
        })
        .catch((error) => console.error('Error sending message:', error));
    }

    function retrieveMessages() {
      // Make an API call to retrieve the messages from the server
      fetch(`${API_BASE_URL}/messages`)
        .then((response) => response.json())
        .then((data) => {
          data.messages.forEach(({ message, sender }) => {
            appendMessage(message, sender);
          });
        })
        .catch((error) => console.error('Error retrieving messages:', error));
    }

    function appendMessage(message, sender) {
      const messageElement = document.createElement('div');
      messageElement.classList.add('message');

      if (sender === 'admin') {
        messageElement.classList.add('admin-message');
        message += ` (${adminName})`; // Display admin name
      } else {
        messageElement.classList.add('user-message');
        message += ` (${userName})`; // Display user name
      }

      messageElement.innerText = message;
      messageContainer.appendChild(messageElement);
      messageContainer.scrollTop = messageContainer.scrollHeight;
    }

    sendButton.addEventListener('click', () => {
      const message = messageInput.value.trim();
      if (message !== '') {
        appendMessage(message, 'user');
        sendMessage(message, 'user');
        messageInput.value = '';
      }
    });

    messageInput.addEventListener('keydown', (event) => {
      if (event.key === 'Enter') {
        sendButton.click();
      }
    });

    // Retrieve messages on page load
    retrieveMessages();
  </script>

Comments

Popular posts from this blog

How to fix SSL Certificate Issues?

How to Fix Website Mixed Content Issues?

How to Fix Mobile Responsiveness Issues?

Popular posts from this blog

How to fix SSL Certificate Issues?

How to Fix Website Mixed Content Issues?

How to Fix Mobile Responsiveness Issues?