forked from Merrcurys/Portfolio-Website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
497 lines (418 loc) · 19.5 KB
/
script.js
File metadata and controls
497 lines (418 loc) · 19.5 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
document.addEventListener('DOMContentLoaded', function () {
// Лабораторная работа 1: Верстка сайта
// Функция расчета возраста
function calculateAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
const monthDiff = today.getMonth() - birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
age--;
}
return age;
}
// Обновление возраста
function updateAge() {
const birthDate = '2006-06-04'; // 4 июня 2006
const age = calculateAge(birthDate);
// Обновляем основной счетчик возраста
const ageDisplay = document.getElementById('ageDisplay');
if (ageDisplay) {
ageDisplay.textContent = age;
}
// Анимированное обновление лет в IT
const codingYears = document.getElementById('codingYears');
if (codingYears) {
const itStartDate = new Date('2020-10-01'); // 1 октября 2021
const now = new Date();
// Рассчитываем точное количество лет с дробями
const diffTime = Math.abs(now - itStartDate);
const msPerYear = 1000 * 60 * 60 * 24 * 365.25; // Миллисекунд в году
const yearsInIT = diffTime / msPerYear;
// Округляем до одного знака после запятой
const displayYears = Math.round(yearsInIT * 10) / 10;
animateDecimalNumber(codingYears, 0, displayYears, 4000);
}
}
// Анимация десятичного числа
function animateDecimalNumber(element, start, end, duration) {
const startTime = performance.now();
function updateNumber(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easeOutQuart = 1 - Math.pow(1 - progress, 4);
const current = start + (end - start) * easeOutQuart;
element.textContent = current.toFixed(1);
if (progress < 1) {
requestAnimationFrame(updateNumber);
}
}
requestAnimationFrame(updateNumber);
}
// Function to update education timeline based on data attributes
function updateEducationTimeline() {
const educationBars = document.querySelectorAll('.education-bar');
const timelineStart = 2021; // Start year of the timeline
const timelineEnd = 2026; // End year of the timeline
const timelineDuration = timelineEnd - timelineStart; // Total timeline duration in years
educationBars.forEach(bar => {
// Parse start date (supporting both "yyyy" and "mm.yyyy" formats)
let startYear, startMonth = 0;
const startData = bar.dataset.start;
if (startData.includes('.')) {
// Format: mm.yyyy
const [month, year] = startData.split('.');
startYear = parseInt(year);
startMonth = parseInt(month) - 1; // Convert to 0-based month
} else {
// Format: yyyy
startYear = parseInt(startData);
}
// Parse end date (supporting both "yyyy"/"mm.yyyy" formats and "current")
let endYear, endMonth = 11; // Default to December (11 in 0-based)
if (bar.dataset.end === 'current') {
const now = new Date();
endYear = now.getFullYear();
endMonth = now.getMonth(); // 0-based month
} else {
if (bar.dataset.end.includes('.')) {
// Format: mm.yyyy
const [month, year] = bar.dataset.end.split('.');
endYear = parseInt(year);
endMonth = parseInt(month) - 1; // Convert to 0-based month
} else {
// Format: yyyy
endYear = parseInt(bar.dataset.end);
}
}
// Convert to decimal years for precise calculation
// Position the start at the beginning of the month and end at the end of the month
const startDecimal = startYear + (startMonth / 12);
const endDecimal = endYear + ((endMonth + 1) / 12); // End at the end of the specified month
const timelineStartDecimal = timelineStart;
const timelineEndDecimal = timelineEnd;
const timelineDurationDecimal = timelineEndDecimal - timelineStartDecimal;
// Calculate position and width based on timeline duration
const startPercent = ((startDecimal - timelineStartDecimal) / timelineDurationDecimal) * 100;
const widthPercent = ((endDecimal - startDecimal) / timelineDurationDecimal) * 100;
// Apply calculated styles
bar.style.marginLeft = `${startPercent}%`;
bar.style.width = `${widthPercent}%`;
});
}
// Run the update function when the page loads
updateEducationTimeline();
// Запускаем обновление возраста
updateAge();
// Анимация смены ролей
const roleText = document.getElementById('roleText');
const roles = ['Python Developer', 'SQL Developer', 'Android Developer', 'Data Analyst'];
let currentRoleIndex = 0;
let isTransitioning = false;
function switchRole() {
if (isTransitioning) return;
isTransitioning = true;
roleText.style.opacity = '0';
setTimeout(() => {
currentRoleIndex = (currentRoleIndex + 1) % roles.length;
roleText.textContent = roles[currentRoleIndex];
roleText.style.opacity = '1';
isTransitioning = false;
}, 300);
}
// Запуск анимации смены ролей каждые 3.5 секунды
setInterval(switchRole, 3500);
// Анимация навигации при скролле
const navbar = document.querySelector('.navbar');
let lastScrollY = window.scrollY;
window.addEventListener('scroll', () => {
if (window.scrollY > 100) {
navbar.style.background = 'rgba(10, 10, 10, 0.7)';
navbar.style.backdropFilter = 'blur(18px) saturate(140%)';
navbar.style.webkitBackdropFilter = 'blur(18px) saturate(140%)';
navbar.style.borderColor = 'rgba(255, 255, 255, 0.15)';
navbar.style.boxShadow = '0 8px 30px rgba(0, 0, 0, 0.35)';
} else {
navbar.style.background = 'rgba(10, 10, 10, 0.6)';
navbar.style.backdropFilter = 'blur(15px) saturate(120%)';
navbar.style.webkitBackdropFilter = 'blur(15px) saturate(120%)';
navbar.style.borderColor = 'rgba(255, 255, 255, 0.12)';
navbar.style.boxShadow = '0 6px 24px rgba(0, 0, 0, 0.3)';
}
// Скрытие/показ навигации при скролле
if (window.scrollY > lastScrollY && window.scrollY > 200) {
navbar.style.transform = 'translateY(-100%)';
} else {
navbar.style.transform = 'translateY(0)';
}
lastScrollY = window.scrollY;
});
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver(function (entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = '1';
entry.target.style.transform = 'translateY(0)';
}
});
}, observerOptions);
// Добавляем наблюдение за элементами
const animatedElements = document.querySelectorAll('.section-header, .about-info, .stat-card');
animatedElements.forEach((element, index) => {
element.style.opacity = '0';
element.style.transform = 'translateY(30px)';
element.style.transition = `opacity 0.8s ease ${index * 0.1}s, transform 0.8s ease ${index * 0.1}s`;
observer.observe(element);
});
// Плавная прокрутка для навигации
const navLinks = document.querySelectorAll('.nav-link');
navLinks.forEach(link => {
link.addEventListener('click', function (e) {
e.preventDefault();
const targetId = this.getAttribute('href');
const targetSection = document.querySelector(targetId);
if (targetSection) {
targetSection.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
// Убираем активное состояние со всех ссылок
navLinks.forEach(l => l.classList.remove('active'));
});
});
// Параллакс эффект для фоновых элементов
window.addEventListener('scroll', () => {
const scrolled = window.pageYOffset;
const parallaxElements = document.querySelectorAll('.floating-shapes .shape');
parallaxElements.forEach((element, index) => {
const speed = 0.5 + (index * 0.1);
element.style.transform = `translateY(${scrolled * speed}px)`;
});
});
// Добавление CSS стилей
const style = document.createElement('style');
style.textContent = `
.navbar {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
`;
document.head.appendChild(style);
// Инициализация всех анимаций
setTimeout(() => {
document.body.classList.add('loaded');
}, 100);
// Функциональность модального сертификата
const modal = document.getElementById('certificateModal');
const modalTitle = document.getElementById('modalTitle');
const certificateImage = document.getElementById('certificateImage');
const modalClose = document.querySelector('.modal-close');
const certificates = {
'python': {
title: 'Сертификат Python',
image: 'img/certificates/python-certificat.jpg'
},
'javascript': {
title: 'Сертификат JavaScript',
image: 'img/certificates/js-certificate.png'
}
};
const clickableTechCards = document.querySelectorAll('.tech-card-clickable');
clickableTechCards.forEach(card => {
card.addEventListener('click', function () {
const certificateType = this.dataset.certificate;
const certificate = certificates[certificateType];
if (certificate) {
modalTitle.textContent = certificate.title;
certificateImage.src = certificate.image;
certificateImage.alt = certificate.title;
modal.classList.add('show');
document.body.style.overflow = 'hidden';
}
});
});
// Закрытие модального окна
function closeModal() {
modal.classList.remove('show');
document.body.style.overflow = '';
}
modalClose.addEventListener('click', closeModal);
modal.addEventListener('click', function (e) {
if (e.target === modal) {
closeModal();
}
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && modal.classList.contains('show')) {
closeModal();
}
});
const modalContent = document.querySelector('.modal-content');
modalContent.addEventListener('click', function (e) {
e.stopPropagation();
});
// Функциональность индикатора прокрутки
const scrollIndicator = document.querySelector('.scroll-indicator');
if (scrollIndicator) {
scrollIndicator.addEventListener('click', function () {
const nextSection = document.querySelector('#about');
if (nextSection) {
nextSection.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
}
// Функциональность кнопки возвращения назад
const backToTopButton = document.getElementById('backToTop');
// Отображение кнопки
window.addEventListener('scroll', function () {
if (backToTopButton) {
if (window.scrollY > 600) { // Show button after scrolling 600px
backToTopButton.classList.add('show');
} else {
backToTopButton.classList.remove('show');
}
}
});
if (backToTopButton) {
backToTopButton.addEventListener('click', function () {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
}
// Наведения курсора на навигационную панель
if (navbar) {
navbar.addEventListener('mouseenter', function () {
this.style.transform = 'translateY(0)';
});
navbar.addEventListener('mouseleave', function () {
if (window.scrollY > 200) {
this.style.transform = 'translateY(-100%)';
}
});
}
// Обработчик формы обратной связи
const contactForm = document.getElementById('contactForm');
if (contactForm) {
contactForm.addEventListener('submit', function (e) {
e.preventDefault();
// Получаем значения полей формы
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const subject = document.getElementById('subject').value;
const message = document.getElementById('message').value;
// В реальном приложении здесь был бы код для отправки данных на сервер
console.log('Форма отправлена:', { name, email, subject, message });
// Показываем сообщение об успешной отправке
alert(`Спасибо, ${name}! Ваше сообщение отправлено.`);
// Очищаем форму
contactForm.reset();
});
}
});
// jQuery функциональность
// Лабораторная работа: Изучение основ JavaScript, библиотек jQuery и jQuery UI
// 1. Метод .ready()
$(document).ready(function () {
// 2. Метод .click() - добавим клик по кнопкам технологий
$('.tech-card').click(function () {
// 3. Метод .addClass() - добавим класс при клике
$(this).addClass('clicked');
// 4. Метод .css() - изменим стиль при клике
$(this).css('border-color', '#00f5ff');
// 5. Метод .animate() - анимируем элемент
$(this).animate({
opacity: 0.8
}, 300, function () {
$(this).animate({
opacity: 1
}, 300);
});
// Применено минимум 5 методов jQuery как требуется в лабораторной работе:
// .ready(), .click(), .addClass(), .css(), .animate()
// Удалим класс через некоторое время
setTimeout(() => {
$(this).removeClass('clicked');
$(this).css('border-color', '');
}, 1000);
});
// Добавим анимацию для навигационных ссылок
$('.nav-link').hover(
function () {
// При наведении
$(this).addClass('hovered');
},
function () {
// При убирании курсора
$(this).removeClass('hovered');
}
);
// Анимация для секций при прокрутке с использованием jQuery
$(window).scroll(function () {
$('.section-title').each(function () {
const elementTop = $(this).offset().top;
const elementBottom = elementTop + $(this).outerHeight();
const viewportTop = $(window).scrollTop();
const viewportBottom = viewportTop + $(window).height();
if (elementBottom > viewportTop && elementTop < viewportBottom) {
// 6. Метод .fadeIn() - плавное появление
$(this).fadeIn();
}
});
});
// Использование jQuery UI - виджет Accordion для списка навыков
// Создадим массив навыков
// Это первый компонент jQuery UI, как требуется в лабораторной работе
const skills = [
{ name: 'Python', level: 90, description: 'Продвинутый уровень. Используется для разработки Telegram ботов, Data Science и веб-приложений.' },
{ name: 'JavaScript', level: 75, description: 'Средний уровень. Используется для фронтенд разработки и интерактивности сайта.' },
{ name: 'HTML/CSS', level: 80, description: 'Продвинутый уровень. Создание адаптивных и современных веб-интерфейсов.' },
{ name: 'SQL', level: 70, description: 'Средний уровень. Работа с базами данных PostgreSQL, MySQL, T-SQL.' },
{ name: 'Git', level: 85, description: 'Продвинутый уровень. Контроль версий, работа в команде, CI/CD.' }
];
// Создадим HTML для accordion
let accordionHtml = '';
skills.forEach((skill, index) => {
accordionHtml += `
<h3>${skill.name}</h3>
<div>
<p>${skill.description}</p>
<p>Уровень владения: ${skill.level}%</p>
<div class="skill-progress">
<div class="skill-progress-bar" style="width: ${skill.level}%"></div>
</div>
</div>`;
});
// Добавим accordion в страницу
$('#skills-accordion').html(accordionHtml);
// Инициализируем jQuery UI Accordion
$('#skills-accordion').accordion({
collapsible: true,
heightStyle: "content",
active: false
});
// Использование jQuery UI - виджет Dialog для модального окна
// Это второй компонент jQuery UI, как требуется в лабораторной работе
$('#open-dialog').click(function () {
$('#dialog-modal').dialog({
modal: true,
width: 400,
height: 300,
buttons: {
"Закрыть": function () {
$(this).dialog("close");
}
}
});
});
// Продемонстрировано 2 компонента из библиотеки jQuery UI как требуется в лабораторной работе:
// 1. Accordion (аккордеон) - для отображения навыков
// 2. Dialog (диалоговое окно) - для модального окна
});