How to: Make a Mini Messenger with JavaScript For Beginners
Hey there, welcome to my first post. So, in this post our goal is to make a Mini Messenger. In this tutorial I’ll be using JavaScript mostly but I will also include a link to my CodePen where you will be able to access the HTML and CSS of this project. This tutorial is aimed at beginners or anyone interested in catching a thing or two.
Getting Started
The messenger I will be making in this tutorial will include a text box where the message will be written and once submitted it will be displayed on the screen for 2 seconds then disappear. I will try to explain as I continue and include code snippets as well, so make sure you try it out by yourself. Here is the CodePen Project in case you need a reference point.
Structure
Below I have provided the structure of my HTML document which will help you understand the some of the classes and elements I will be referring to as We go along.
!DOCTYPE html> lang="en">Messengerrel="stylesheet"href="style.css">class="main">A Message You would like to passclass="message-form">type="text"class="typedMessage"placeholder="Type Your Message. "autofocus>class="submit">SendLast Message Deliveredclass="messages">
src="app.js">
Add a message
To start off I need to set up an array that will hold our messages. Each message will be an object with two properties, text and id . text will be used to store the message that has been typed by the user and the id will be used to give the message a unique number . They will all be stored within the chat object within the addMessage() function.
//Create an array where the message along with it's ID will be stored.letmessage=[];// This fuction will enables us to add the message to the DOMfunctionaddMessage(text) //Object where message will be storedconstchat=text,id:Date.now()>message.push(chat);console.log(message);>
Next I will add an event listener to listen for the submit event within the input form .message-form . Inside the form I have a text input which has a class called .typedMessage . The event will store the message within the input constant.
//Create event listener to detect when a message has been submittedconstform=document.querySelector('.message-form');form.addEventListener('submit',event=>event.preventDefault();//input to save the message itselfconstinput=document.querySelector('.typedMessage');//This helps us to detect empty messages and ignore themconsttext=input.value.trim();if(text!=='') addMessage(text);input.value='';input.focus();>>);
Then the .trim() method will be used to remove extra space from the beginning of the message at the end of the message. This will help us to know whether the string is empty or not. If the message is empty it will be ignored. If not empty, then it will be passed through the addMessage() function, the input field will be cleared and be focused on. The Date.now() function allows us to create unique ID for each message. It returns the number of elapsed milliseconds since January 1, 1970 This will assist you when you want to refer to a specific message for other features you may wish to include such as a delete button. Up to where I’ve reached if you type a message in your text box you should be able to see the output of your message and ID in the console.
Render the Message
After the message has been pushed to the array, I now want to be able to display it on the page, and I will do this by adding a p element with the message to a class in our html called .messages . Replace the console.log() statement in the addMessage() as follows:
functionaddMessage(text) //Object where message will be storedconstchat=text,id:Date.now()>message.push(chat);//Render message to the screenconstlist=document.querySelector('.messages');list.insertAdjacentHTML('beforeend',`
$chat.id>"> $chat.text>
`);>
In the list constant I select the .messages class and I use the insertAdjacentHTML() method to insert the html code into the html document specifically beforeend , which means just inside the element, after its last child. After this you should be able to type your message and it will be displayed on the screen.
Add Timer
So far our app is working great, but I want the message I wrote to disappear after 2 seconds. To achieve this I will make use of the setTimeout() method which executes only once after a certain period of time. This method takes two main parameters which are function to be executed and the delay in milliseconds . Add the timer variable last in the addMessage() function.
functionaddMessage(text) //Object where message will be storedconstchat=text,id:Date.now()>message.push(chat);//Render message to the screenconstlist=document.querySelector('.messages');list.insertAdjacentHTML('beforeend',`
$chat.id>"> $chat.text>
`);// Delete the message from the screen after 2 secondslettimer=setTimeout(()=>Array.from(list.children).forEach((child)=>list.removeChild(child))clearTimeout(timer);>,2000);>
Within the setTimeout() I create an arrow function, then I use Array.from() to create a method that selects all the children within the list variable. Next I use a .forEach() method which executes an arrow function that removes all the children from the list variable. Then finally I use clearTimeout(timer) that cancels the timer that I set. After the function parameter I also remember to include the time limit which is 2000 milliseconds for 2 seconds. Here is a link to the finished version on CodePen Thank You for taking your time to read this. I hope it has helped you or given you an idea of what you can make using the same concepts I used. Feel free to share with your friends and let me know your thoughts or an idea you would like to see in my future posts. If you do make your own version tag me in it on Twitter i’d love to see what you made. See you in the next one ✌🏼.
В этом уроке мы будем создавать простое приложение веб-чата с помощью PHP и jQuery. Утилита такого типа прекрасно подойдет для системы онлайн-поддержки вашего сайта.
Введение
Приложение чата, которое мы сегодня построим, будет довольно простым. Оно будет включать в себя систему входа и выхода, возможности в AJAX-стиле, а также предложит поддержку нескольких пользователей.
Шаг 1: HTML разметка
Мы начнем этот урок с создания нашего первого файла index.php.
Мы начнем наш html с обычных DOCTYPE, html, head, и body тагов. В таг head мы добавим наш заголовок и ссылку на нашу таблицу стилей css (style.css).
Внутри тага body, мы структурируем наш макет внутри блока — обертки #wrapper div. У нас будет три главных блока: простое меню, окно чата и поле ввода нашего сообщения; каждый со своим соответствующим div и id.
Блок меню #menu div будет состоять из двух абзацев. Первый будет приветствием пользователю и поплывет налево, а второй будет ссылкой на выход и поплывет направо. Мы также включим блок div для очистки элементов.
Блок чата #chatbox div будет содержать лог нашего чата. Мы будем загружать наш лог из внешнего файла с использованием ajax-запроса jQuery.
Последним пунктом в нашем блоке-обертке #wrapper div будет наша форма, которая будет включать в себя текстовое поле ввода для сообщения пользователя и кнопку отправки.
Шаг 2: Создание стиля CSS
Теперь мы добавим немного css, чтобы заставить наше приложение чата выглядеть лучше, чем стиль браузера по умолчанию. Код, указанный ниже будет добавлен в наш файл style.css.
a:hovertext-decoration:underline;>
#loginformpadding-top:18px;>
#menupadding:12.5px25px12.5px25px;>
В вышеуказанном css нет ничего особенного, кроме того факта, что некоторые id или классы, для которых мы устанавливаем стиль, будут добавлены немного позже.
Как вы можете видеть выше, мы закончили строить пользовательский интерфейс чата.
Шаг 3: Используем PHP, чтобы создать форму входа.
Теперь мы реализуем простую форму, которая будет спрашивать у пользователя его имя, перед тем, как пустить его дальше.
Функция loginForm(), которую мы создали, состоит из простой формы входа, которая спрашивает у пользователя его/ее имя. Затем мы используем конструкцию if else, чтобы проверить, ввел ли пользователь имя. Если человек ввел имя, мы устанавливаем его, как $_SESSION[‘имя’]. Так как мы используем сессию, основанную на cookie, чтобы хранить имя, мы должны вызвать session_start() перед тем, как что-нибудь выводить в браузер.
Есть одна вещь, на которую вы возможно захотите обратить особое внимание — то, что мы использовали функцию htmlspecialchars(), которая конвертирует специальные символы в HTML сущности, тем самым защищая имя переменной, чтобы оно не стало жертвой межсайтового скриптинга (XSS). Мы также добавим эту функцию позже к текстовой переменной, которая будет опубликована в логе чата.
Отображение формы входа
Для того, чтобы показать форму логина в случае, если пользователь не вошел в систему, и следовательно, не сессия не создалась, мы используем другую инструкцию if else вокруг блока-обертки #wrapper div и тагов скрипта в нашем исходном коде. В противоположном случае, если пользователь вошел в систему и создал сессию, этот код спрячет форму входа и покажет окно чата.
Мы еще не закончили создавать систему входа для этого приложения чата. Нам еще нужно дать пользователю возможность выйти из системы и закончить сессию чата. Как вы помните, наша исходная HTML разметка включала в себя простое меню. Давайте вернемся назад и добавим некоторый PHP код, который придаст меню больше функциональности.
Прежде всего, давайте добавим имя пользователя в сообщение приветствия. Мы сделаем это, выводя сессию имени пользователя.
class="welcome">Welcome, echo$_SESSION['name'];?>
Для того, чтобы позволить пользователю выйти из системы и завершить сессию, мы прыгнем выше головы и кратко используем jQuery.
//If user wants to end session
var exit = confirm("Are you sure you want to end the session?");
Код jquery, приведенный выше просто показывает диалог подтверждения, если пользователь кликнет по ссылке выхода #exit. Если пользователь подтвердит выход, тем самым решив закончить сессию, мы отправим его в index.php?logout=true. Это просто создаст переменную с именем logout со значением true. Мы должны перехватить эту переменную с помощью PHP:
fwrite($fp,"User ".$_SESSION['name']." has left the chat session. ");
header("Location: index.php");//Redirect the user
Теперь мы увидим, существует ли get переменная ‘logout’, используя функцию isset(). Если переменная была передана через url, такой, как ссылка, упомянутая выше, мы переходим к завершению сессии пользователя с текущим именем.
Перед уничтожением сессии пользователя с текущим именем с помощью функции session_destroy() мы хотим выводить простое сообщение о выходе в лог чата. В нем будет сказано, что пользователь покинул сессию чата. Мы сделаем это, используя функции fopen(), fwrite() и fclose(), чтобы манипулировать нашим файлом log.html, который, как мы увидим позднее, будет создан в качестве лога нашего чата. Пожалуйста, обратите внимание, что мы добавили класс ‘msgln’ в блок div. Мы уж определили стиль css для этого блока.
Проделав это, мы уничтожаем сессию и перенаправляем пользователя на ту же страницу, где появится форма входа в систему.
Шаг 4: Поддержка пользовательского ввода данных
После того, как пользователь подтвердил свои действия в нашей форме, нам нужно захватывать его ввод с клавиатуры и писать его в лог нашего чата. Для того, чтобы сделать это, мы должны использовать jQuery и PHP, чтобы работать синхронно на стороне сервера и на стороне клиента.
jQuery
Практически все, что мы собираемся делать с jQuery для обработки наших данных, будет вращаться вокруг запроса на jQuery post.