-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
119 lines (116 loc) · 5.29 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Подключение Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<title>Чат программа</title>
<!-- Подклучаем стили -->
<style>
body {
background: #fcfcfc;
}
</style>
</head>
<body>
<!-- Создание меню на сайте (без функций) -->
<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm">
<h5 class="my-0 mr-md-auto">Чат</h5>
<nav class="my-2 my-md-0 mr-md-3">
<a class="p-2 text-dark" href="#">Главная</a>
<a class="p-2 text-dark" href="#">Про нас</a>
<a class="p-2 text-dark" href="#">Поддержка</a>
<a class="p-2 text-dark" href="#">Цены</a>
</nav>
<a class="btn btn-outline-primary" href="#">Регистрация</a>
</div>
<!-- Основная часть страницы -->
<div class="container">
<div class="py-5 text-center">
<h2>Чат программа</h2>
<p class="lead">Укажите ваше имя и начинайте переписку</p>
</div>
<div class="row">
<div class="col-6">
<!-- Форма для получения сообщений и имени -->
<h3>Форма сообщений</h3>
<form id="messForm">
<label for="name">Имя</label>
<input type="text" name="name" id="name" placeholder="Введите имя" class="form-control">
<br>
<label for="message">Сообщение</label>
<textarea name="message" id="message" class="form-control" placeholder="Введите сообщение"></textarea>
<br>
<input type="submit" value="Отправить" class="btn btn-danger">
</form>
</div>
<div class="col-6">
<h3>Сообщения</h3>
<!-- Вывод всех сообщений будет здесь -->
<div id="all_mess"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
// У каждого пользователя будет случайный стиль для блока с сообщенями,
// поэтому в этом кусочке кода мы получаем случайные числа
let min = 1;
let max = 6;
let random = Math.floor(Math.random() * (max - min)) + min;
// Устаналиваем класс в переменную в зависимости от случайного числа
// Эти классы взяты из Bootstrap стилей
let alertClass;
switch (random) {
case 1:
alertClass = 'secondary';
break;
case 2:
alertClass = 'danger';
break;
case 3:
alertClass = 'success';
break;
case 4:
alertClass = 'warning';
break;
case 5:
alertClass = 'info';
break;
case 6:
alertClass = 'light';
break;
}
// Функция для работы с данными на сайте
$(function(){
// Включаем socket.io и отслеживаем все подключения
let socket = io.connect()
// Делаем переменные на:
let $form = $("#messForm") // Форму сообщений
let $name = $("#name") // Поле с именем
let $textarea = $("#message") // Текстовое поле
let $all_messages = $("#all_mess") // Блок с сообщениями
// Отслеживаем нажатие на кнопку в форме сообщений
$form.submit((event) => {
// Предотвращаем классическое поведение формы
event.preventDefault()
// В сокет отсылаем новое событие 'send mess',
// в событие передаем различные параметры и данные
socket.emit("send mess", {mess: $textarea.val(), name: $name.val()})
// Очищаем поле с сообщением
$textarea.val(" ")
})
// Здесь отслеживаем событие 'add mess',
// которое должно приходить из сокета в случае добавления нового сообщения
socket.on('add mess', (data) => {
// Встраиваем полученное сообщение в блок с сообщениями
// У блока с сообщением будет тот класс, который соответвует пользователю что его отправил
$all_messages.append("<div><b>" + data.name + "</b>: " + data.mess + "</div>")
})
})
</script>
</body>
</html>