Messaging system front-end

Overview

The frontend is written in plain JavaScript with Bootstrap. It handles:

  • Group creation via modal

  • Search and dynamic UI for group member selection

  • Chat selection and lazy-loaded message rendering

  • Auto-scrolling and polling for updates

  • Sidebar for group information

  • Form submission for sending messages

Runs on DOMContentLoaded:

document.addEventListener('DOMContentLoaded', () => { /* init */ });

🔁 Event Flow Summary

1. Setup

Selects elements and initializes state:

const messagesContainer = document.querySelector('.messages');
const chatItems = document.querySelectorAll('.chat-item');
const userId = parseInt(document.getElementById('user-data')?.dataset.userId || '0');

Flags:


👥 Group Chat Creation

Resets modal UI and shows modal:

Query /search-global?q=term after 2+ characters:

Results are shown with “Add” buttons. Selected users are pushed into groupSelected:

Selected Users UI

Render list and generate hidden inputs for backend:

Disable submit if < 2 users:


💬 Chat View Logic

Chat Selection

Every .chat-item has a click handler:

Avoids reloading same chat:

Sets form hidden fields:

Message Rendering

Group chats show sender name and avatar if not self:

Adds date dividers using:


🔄 Message Polling (Refresh)

Polling happens every 3.5s only if user is near the bottom:

Polling control:

Tab visibility is respected:


📝 Sending Messages

Intercept form submission:

Send via AJAX to /send-message:

On success: refresh messages On failure: show alert and restore input


🧾 Group Sidebar Panel

Show/Hide

Hides on outside click:

Populate Content

Render Members

Navigation and removal:


📌 Special Features

Chat ID in URL

Auto-selects the chat from ?currentChatId=<id>:


Scroll Button

Shows or hides #scroll-to-bottom-btn:

Scroll to bottom smoothly:


📂 DOM Elements

Selector
Function

#new-chat-btn

Opens modal for group creation

#groupUserSearch

Search input field

#groupUserResults

Search result container

#groupSelectedUsers

User list in modal

#groupHiddenInputs

Hidden inputs for form

#message-form

Message input form

.messages

Main message panel

.ChatInfo

Top chat bar

.chat-item

Left-panel chat selectors

#group-options-btn

Opens group sidebar

#group-info-sidebar

Sidebar container


⚠️ Error Handling

Network/Timeout

Handled with AbortController:

Error UI feedback

AJAX failures show alerts dynamically:

All errors render fallback UIs, e.g.,

Last updated