Building a Chat Application with HTML CSS and JavaScript

0

hey everybody hope you are all fine, today we are going to learn how to build a chat application using HTML CSS and JavaScript from scratch. In today’s digital era, communication is key, and creating a chat application using fundamental web technologies like HTML, CSS, and JavaScript can be an exciting and educational project.

This article will guide you through the basic steps involved in creating a simple yet functional chat application. HTML, CSS, and JavaScript are the building blocks of the web.

Chat Application with HTML CSS and JavaScript

Before moving the codes, you can watch the tutorial because I explained everything from scratch how to use HTML CSS and JavaScript to create it step by step. I hope you will learn many new things from this tutorial.

After watching the complete tutorial, I hope you’ve learned something new from this tutorial. If you face any problem you can check it now the source code that I used inside the video.

You May Also Like:

HTML provides the structure, CSS beautifies the elements, and JavaScript brings interactivity to the table. When combined, these languages can be used to construct a straightforward chat application.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="css/style.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    />
    <script defer src="js/script.js"></script>
    <title>Chat App using HTML CSS & JS | OnlineITtuts</title>
  </head>
  <body>
    <div class="container">
      <div class="cards">
        <div class="card-header">
          <h2>Chat Application</h2>
        </div>
        <div class="card-body">
          <!-- <div class="chat chat-bot">
            <span class="user-icon"><i class="fa fa-robot"></i></span>
            <p>May I Help You Today?</p>
          </div>
          <div class="chat user">
            <span class="user-icon"><i class="fa fa-user"></i></span>
            <p>How to use Filter Method in JS?</p>
          </div> -->
        </div>
        <div class="card-footer">
          <textarea
            name="message"
            class="input-chat"
            id=""
            cols="10"
            rows="1"
            placeholder="Ask me Anything......"
          ></textarea>
          <div class="sending-icon">
            <i class="fa-regular fa-paper-plane"></i>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

The user interface is the first impression of any application. Using HTML and CSS, you can craft a clean and intuitive design for your chat application. Utilize HTML to create the structure of the chat interface—defining elements like the chat window, input field, and message display area. CSS can then be employed to style these elements, making the interface visually appealing and user-friendly.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&family=Ruda:wght@400;600;700&display=swap");

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  font-family: "poppins", sans-serif;
  background-color: #c9d6ff;
  background: linear-gradient(to right, #e2e2e2, #c9d6ff);
}

.container {
  width: 640px;
  background-color: #17202a;
  border-radius: 10px;
  box-shadow: 5px 0 10px rgba(0, 0, 0, 0.3);
  position: relative;
}

.card-header {
  background-color: #212f3d;
  border-radius: 10px 10px 0 0;
  padding: 1rem;
  color: #fff;
  width: 100%;
}

.card {
  overflow-y: auto;
}

::-webkit-scrollbar {
  width: 05px;
}

::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb {
  background: #2c3e50;
  border-radius: 5px;
}

.card-body {
  padding: 0.8rem;
  font-size: 1rem;
  height: 600px;
  overflow-y: auto;
}

.card-body .chat-bot {
  display: flex;
  align-items: center;
}

.card-body .user {
  display: flex;
  align-items: center;
  justify-content: end;
}

.card-body .chat-bot p {
  background-color: #3498db;
  border-radius: 10px;
  padding: 0.8rem;
  width: 50%;
  white-space: pre-wrap;
}

.card-body .user p {
  background-color: #28b463;
  border-radius: 10px;
  padding: 0.8rem;
  width: 50%;
  white-space: pre-wrap;
}

.chat-bot,
.user {
  margin: 1rem 0;
}

.chat .user-icon {
  width: 45px;
  height: 45px;
  font-size: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50px;
  margin-right: 0.5rem;
  border: 2px solid #212f3d;
}

.user-icon .fa-robot {
  color: #3498db;
}

.user-icon .fa-user {
  color: #28b463;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 2rem 0;
}

.card-footer textarea {
  resize: none;
  border: none;
  outline: none;
  font-family: inherit;
  width: 100%;
  display: flex;
  padding: 1.5rem;
  background-color: #212f3d;
  border-radius: 10px;
  color: #fff;
  font-size: 1rem;
  position: absolute;
  bottom: 0;
}

.sending-icon {
  position: absolute;
  right: 30px;
}

.sending-icon .fa-paper-plane {
  color: #fff;
  font-size: 1.5rem;
  cursor: pointer;
}

Implementing Functionality with JavaScript

JavaScript is where the magic happens. It enables the application to interact with users and handle the real-time aspects of a chat system. With JavaScript, you can capture user input, send and receive messages, and update the chat interface dynamically without the need to refresh the page.

"use strict";

const inputEl = document.querySelector(".input-chat");
const btnEl = document.querySelector(".fa-paper-plane");
const cardBodyEl = document.querySelector(".card-body");

let userMessage;
const API_KEY = "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";
const URL = "https://api.openai.com/v1/chat/completions";

const chatGenerator = (robot) => {
  robot = robot.querySelector(".robot");
  const requestOption = {
    method: "POST",
    headers: {
      "content-type": "application/json",
      authorization: `Bearer ${API_KEY}`,
    },
    body: JSON.stringify({
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: userMessage,
        },
      ],
    }),
  };

  fetch(URL, requestOption)
    .then((res) => res.json())
    .then((data) => {
      robot.textContent = data.choices[0].message.content;
    })
    .catch((error) => {
      robot.textContent = error;
    });
};

// manage chat
function manageChat() {
  userMessage = inputEl.value.trim();

  if (!userMessage) return;
  inputEl.value = "";

  cardBodyEl.appendChild(messageEl(userMessage, "user"));

  setTimeout(() => {
    const robotMessage = messageEl("Thinking...........", "chat-bot");
    cardBodyEl.append(robotMessage);
    chatGenerator(robotMessage);
  }, 600);
}

// messages
const messageEl = (message, className) => {
  const chatEl = document.createElement("div");
  chatEl.classList.add("chat", `${className}`);
  let chatContent =
    className === "chat-bot"
      ? `<span class="user-icon"><i class="fa fa-robot"></i></span>
  <p class='robot'>${message}</p>`
      : ` <span class="user-icon"><i class="fa fa-user"></i></span>
  <p>${message}</p>`;
  chatEl.innerHTML = chatContent;
  return chatEl;
};

btnEl.addEventListener("click", manageChat);

inputEl.addEventListener("input", (e) => {
  e.preventDefault();
  e.target.addEventListener("keydown", (keyboard) => {
    if (keyboard.key === "Enter") {
      manageChat();
    }
  });
});

Utilize JavaScript to handle events such as sending messages, displaying incoming messages, and managing the chat history. You can employ techniques like AJAX requests to send and retrieve data from a server, providing a seamless chat experience.

While a basic chat application can be built with HTML, CSS, and JavaScript alone, integrating additional technologies can enhance its functionality. For instance, using a backend technology like Node.js along with a database can enable real-time communication between users and store chat history.

Additionally, integrating WebSocket technology can facilitate real-time, bidirectional communication between the client and the server, making the chat application more responsive and efficient.

When developing a chat application, consider security measures to protect user data and prevent unauthorized access. Implement authentication processes and encryption techniques to ensure the safety of users’ conversations.

Moreover, scalability is essential for a successful chat application. As the user base grows, the application should be capable of handling increased traffic and user interactions. Employing efficient database structures and server architectures can ensure the scalability of the application.

Conclusion

Creating a chat application using HTML, CSS, and JavaScript is an enriching project that combines design, functionality, and interactivity. It showcases the power of these fundamental web technologies in building a real-time communication platform.

Remember, this is a foundational project. As you delve deeper into web development, you’ll encounter more sophisticated frameworks and libraries that can streamline the development process and offer more advanced features. However, starting with the basics provides a strong understanding of how these technologies work together to create a functional application.

Happy coding!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.