Send/Recieve Files Online (Recieve Files by Enter 6 Digit Code) 👉

X
Code copied to clipboard!

POMSD

Advertisement

How to Create Chat Application in HTML, Css, Js || Blogger and Website

 

How to Create Chat Application in HTML, Css, Js || Blogger and Website


Hello Dosto  Aaj me aapke liye chat application ka source code laya hu jise aap online chat aaplicaton bna sakte hai or isme aapko login panel bhi add hai to code neeche diya gaya hai jakar copy kar lijiyega. 


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chat Online</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 30px;
      background-color: #f4f4f4;
      
    }
    .chat-container {
      max-width: 100%;
      margin: 20px auto;
      border: 1px solid #ccc;
      border-radius: 5px;
      overflow: hidden;
    }
    .chatmsg {
      padding: 10px;
      overflow-y: scroll;
      height: 250px;
      background-color: #fff;
    }
    .message {
      padding: 5px 10px;
      margin: 5px 0;
      border-radius: 5px;
      background-color: #f2f2f2;
      position: relative;
      cursor: pointer;
    }
    .message.sent {
      background-color: #dcf8c6;
      align-self: flex-end;
    }
    .message.received {
      background-color: #eaeaea;
    }
    .message:hover {
      background-color: #d9d9d9;
    }
    .quoted-message {
      padding: 0px;
      margin-bottom: 0px;
      border-left: 0px solid #4CAF50;
      background-color: #f000;
      font-size: 0px;
    }
    
    .quoted-message p {
      margin: 0;
    }
    .chat-input {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      background-color: #fff;
    }
    .chat-input input[type="text"], .chat-input input[type="file"] {
      flex: 1;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 20px;
    }
    .chat-input button {
      padding: 8px 20px;
      border: none;
      border-radius: 20px;
      background-color: #4CAF50;
      color: white;
      cursor: pointer;
    }
    .chat-input button:hover {
      background-color: #45a049;
    }
    .image-preview {
      max-width: 100%;
      height: auto;
      margin-top: 5px;
    }
    .typing-indicator {
      margin-top: 5px;
      color: #888;
    }
    .online-count {
      margin-top: 5px;
      color: #888;
    }
    .login-container {
      max-width: 400px;
      margin: 100px auto;
      padding: 20px;
      background-color: #fff;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    .login-container h2 {
      margin-top: 0;
      text-align: center;
    }
    .login-form input[type="email"],
    .login-form input[type="password"],
    .login-form input[type="text"] {
      width: 100%;
      margin-bottom: 10px;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }
    .login-form button {
      width: 100%;
      padding: 10px;
      border: none;
      border-radius: 20px;
      background-color: #4CAF50;
      color: white;
      cursor: pointer;
    }
    .login-form button:hover {
      background-color: #45a049;
    }
    .signup-form {
      display: none;
    }
    .avatar {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      margin-right: 10px;
    }
  </style>
</head>
<body>

<audio id="new-message-sound" src="https://www.soundjay.com/button/beep-07.wav" preload="auto"></audio>

<div class="login-container">
  <h2>Login</h2>
  <form class="login-form" id="login-form"onsubmit="return sendMessage();">
    <input type="email" id="email" placeholder="Email" required>
    <input type="password" id="password" placeholder="Password" required>
    <button type="submit">Login</button>
  </form>
  <div class="signup-form">
    <h2>Sign Up</h2>
    <form id="signup-form">
      <input type="email" id="signup-email" placeholder="Email" required>
      <input type="password" id="signup-password" placeholder="Password" required>
      <input type="text" id="signup-username" placeholder="Username" required>
      <input type="text" id="signup-avatar" placeholder="Avatar URL" required>
      <button type="submit">Sign Up</button>
    </form>
  </div>
  <p>Don't have an account? <a href="#" id="show-signup">Sign Up</a></p>
</div>

<div class="chat-container" id="chat-container" style="display: none;" >
<!--  <h2>Set Your Username</h2> -->
  <input type="text" id="username-input" placeholder="" required>
  <h id="set-username-btn"></h>
  <div class="chatmsg" id="messages"></div>
  <div class="typing-indicator" id="typing-indicator"></div>
  <div class="online-count" id="online-count"></div>
  <div class="chat-input">
    <input type="file" id="image-input" accept="image/*">
    <input type="text" id="message-input" placeholder="Type a message...">
    <button id="send-btn">Send</button>
  </div>
</div>

<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-storage.js"></script>
<script>
  // Your Firebase configuration
  const firebaseConfig = {
       apiKey: "AIzaSyDLkb_EorKDUd900mZjEgtkeK8WhwNdtck",
        authDomain: "capable-acrobat-371505.firebaseapp.com",
        databaseURL: "https://capable-acrobat-371505-default-rtdb.firebaseio.com/",
        projectId: "capable-acrobat-371505",
        storageBucket: "capable-acrobat-371505.appspot.com",
        messagingSenderId: "11271908647",
        appId: "1:112719086471:web:b7d187dc6bd7baaee50922"

  };

  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

  const auth = firebase.auth();
  const messagesRef = firebase.database().ref('messages');
  const typingRef = firebase.database().ref('typing');
  const presenceRef = firebase.database().ref('.info/connected');
  const usersRef = firebase.database().ref('users');
  const storageRef = firebase.storage().ref();
  const newMessageSound = document.getElementById('new-message-sound');

  const chatContainer = document.getElementById('chat-container');
  const loginContainer = document.querySelector('.login-container');
  const loginForm = document.getElementById('login-form');
  const signupForm = document.getElementById('signup-form');
  const emailInput = document.getElementById('email');
  const passwordInput = document.getElementById('password');
  const signupEmailInput = document.getElementById('signup-email');
  const signupPasswordInput = document.getElementById('signup-password');
  const signupUsernameInput = document.getElementById('signup-username');
  const signupAvatarInput = document.getElementById('signup-avatar');
  const setUsernameButton = document.getElementById('set-username-btn');
  const messages = document.getElementById('messages');
  const messageInput = document.getElementById('message-input');
  const imageInput = document.getElementById('image-input');
  const sendButton = document.getElementById('send-btn');
  const typingIndicator = document.getElementById('typing-indicator');
  const onlineCount = document.getElementById('online-count');
  const showSignupLink = document.getElementById('show-signup');

  let typingTimer;
  const typingTimeout = 1000; // 1 second

  loginForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const email = emailInput.value;
    const password = passwordInput.value;
    auth.signInWithEmailAndPassword(email, password)
      .then(() => {
        loginContainer.style.display = 'none';
        chatContainer.style.display = 'block';
      })
      .catch((error) => {
        alert(error.message);
      });
  });

  signupForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const email = signupEmailInput.value;
    const password = signupPasswordInput.value;
    const username = signupUsernameInput.value.trim();
    const avatar = signupAvatarInput.value.trim();
    auth.createUserWithEmailAndPassword(email, password)
      .then(() => {
        if (username !== '') {
          const userRef = usersRef.child(username);
          userRef.set({
            username: username,
            avatar: avatar
          });
        }
        loginContainer.style.display = 'none';
        chatContainer.style.display = 'block';
      })
      .catch((error) => {
        alert(error.message);
      });
  });

  showSignupLink.addEventListener('click', (e) => {
    e.preventDefault();
    loginForm.reset();
    signupForm.reset();
    loginContainer.querySelector('.signup-form').style.display = 'block';
  });

  let userName;

  auth.onAuthStateChanged((user) => {
    if (user) {
      userName = user.email.split('@')[0];
      initChat();
    } else {
      loginContainer.style.display = 'block';
      chatContainer.style.display = 'none';
    }
  });

  function initChat() {
    let userRef = usersRef.child(userName);

    presenceRef.on('value', (snapshot) => {
      if (snapshot.val()) {
        userRef.onDisconnect().remove();
        userRef.set(true);
      }
    });

    usersRef.on('value', (snapshot) => {
      const count = snapshot.numChildren();
      onlineCount.textContent = count === 1 ? '1 user online' : count + ' users online';
    });

    setUsernameButton.addEventListener('click', () => {
      const newUserName = usernameInput.value.trim();
      if (newUserName !== '') {
        userRef.remove();
        userName = newUserName;
        userRef = usersRef.child(userName);
        userRef.set(true);
      }
    });

    messageInput.addEventListener('input', () => {
      clearTimeout(typingTimer);
      if (messageInput.value) {
        typingRef.set({
          user: userName,
          typing: true
        });
        typingTimer = setTimeout(() => {
          typingRef.set({
            user: userName,
            typing: false
          });
        }, typingTimeout);
      } else {
        typingRef.set({
          user: userName,
          typing: false
        });
      }
    });

    sendButton.addEventListener('click', () => {
      sendMessage();
    });

    messageInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        e.preventDefault(); // Prevent the default behavior of the Enter key
        sendMessage();
      }
    });

    function sendMessage() {
      const messageText = messageInput.value.trim();
      const file = imageInput.files[0];
      if (messageText !== '' || file) {
        if (file) {
          uploadImage(file);
        } else {
          saveMessage(messageText, userName, null);
        }
        messageInput.value = '';
        imageInput.value = '';
        typingRef.set({
          user: userName,
          typing: false
        });
      }
    }

    function saveMessage(messageText, userName, imageUrl) {
      messagesRef.push({
        message: messageText,
        userName: userName,
        imageUrl: imageUrl,
        timestamp: firebase.database.ServerValue.TIMESTAMP
      });
    }

    function uploadImage(file) {
      const imageRef = storageRef.child('images/' + file.name);
      imageRef.put(file).then((snapshot) => {
        snapshot.ref.getDownloadURL().then((imageUrl) => {
          saveMessage('', userName, imageUrl);
        });
      });
    }

    messagesRef.on('child_added', (snapshot) => {
      const messageData = snapshot.val();
      const messageElement = document.createElement('div');
      messageElement.classList.add('message');
      
      const avatarElement = document.createElement('img');
      avatarElement.classList.add('avatar');
      if (messageData.userName === userName) {
        avatarElement.src = 'https://upload.wikimedia.org/wikipedia/commons/2/2d/Basic_green_dot.png'; // Sender's avatar
      } else {
        avatarElement.src = messageData.avatar || 'https://upload.wikimedia.org/wikipedia/commons/7/7c/GAudit_YellowDot.png'; // User's avatar from database or default avatar
      }
      
      const contentElement = document.createElement('div');
      contentElement.classList.add('message-content');
      
      const usernameElement = document.createElement('span');
      usernameElement.textContent = messageData.userName + ': ';
      
      const messageTextElement = document.createElement('span');
      messageTextElement.textContent = messageData.message;
      
      contentElement.appendChild(usernameElement);
      contentElement.appendChild(messageTextElement);
      
      messageElement.appendChild(avatarElement);
      messageElement.appendChild(contentElement);

      if (messageData.imageUrl) {
        const imageElement = document.createElement('img');
        imageElement.classList.add('image-preview');
        imageElement.src = messageData.imageUrl;
        messageElement.appendChild(imageElement);
      }
      if (snapshot.key) {
        messageElement.setAttribute('data-id', snapshot.key);
      }
      messageElement.addEventListener('dblclick', () => {
        const quotedMessage = document.createElement('div');
        quotedMessage.classList.add('quoted-message');
        const quotedText = document.createElement('p');
        quotedText.textContent = messageData.userName + ': ' + messageData.message;
        quotedMessage.appendChild(quotedText);
        messageInput.value = '';
        messageInput.focus();
        messageInput.placeholder = 'Replying to: ' + messageData.userName;
        messages.insertBefore(quotedMessage, messages.firstChild);
      });
      messages.appendChild(messageElement);
      messages.scrollTop = messages.scrollHeight;
      if (messageData.userName !== userName) {
        playNewMessageSound(); // Play sound when new message is added, excluding sender
      }
    });

    typingRef.on('value', (snapshot) => {
      const typingData = snapshot.val();
      if (typingData && typingData.typing) {
        typingIndicator.textContent = typingData.user + ' is typing...';
      } else {
        typingIndicator.textContent = '';
      }
    });
  }

  function playNewMessageSound() {
    newMessageSound.play();
  }

</script>

<script>
    function sendMessage() {
        // get message
        var message = document.getElementById("message").value;
 
        // save in database
        firebase.database().ref("messages").push().set({
            "sender": myName,
            "message": message
        });
 
        // prevent form from submitting
        return false;
    }
</script>

<script>
    // listen for incoming messages
    firebase.database().ref("message-input").on("child_added", function (snapshot) {
        var html = "";
        // give each message a unique ID
        html += "<li id='message-input-" + snapshot.key + "'>";
        // show delete button if message is sent by me
        if (snapshot.val().sender == myName) {
            html += "<button data-id='" + snapshot.key + "' onclick='deleteMessage(this);'>";
                html += "Delete";
            html += "</button>";
        }
        html += snapshot.val().sender + ": " + snapshot.val().message;
        html += "</li>";
 
        document.getElementById("message-input").innerHTML += html;
    });
    
    
function deleteMessage(self) {
    // get message ID
    var messageId = self.getAttribute("data-id");
 
    // delete message
    firebase.database().ref("message-input").child(messageId).remove();
}
 
// attach listener for delete message
firebase.database().ref("message-input").on("child_removed", function (snapshot) {
    // remove message node
    document.getElementById("message-input-" + snapshot.key).innerHTML = "This message has been removed";
});
</script>


</body>
</html>







Contact Us!

Comment Box

0 Comments