// script.js для сайта "Самовыкупы"
document.addEventListener('DOMContentLoaded', function() {
// ===== ПЛАВНАЯ ПРОКРУТКА ДЛЯ ЯКОРЕЙ =====
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
// ===== ОБРАБОТКА ФОРМ =====
// Форма в герое
const heroForm = document.getElementById('hero-form');
if (heroForm) {
heroForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
processFormSubmission(formData, 'Форма в герое');
showSuccessMessage('Спасибо! Мы свяжемся с вами в течение 15 минут для расчета стоимости.');
this.reset();
});
}
// Форма калькулятора
const calcForm = document.getElementById('calc-form');
if (calcForm) {
calcForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
processFormSubmission(formData, 'Форма калькулятора');
showSuccessMessage('Спасибо! Менеджер свяжется с вами в течение 15 минут с точным расчетом.');
this.reset();
});
}
// Форма в футере
const footerForm = document.getElementById('footer-form');
if (footerForm) {
footerForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
processFormSubmission(formData, 'Форма в футере');
showSuccessMessage('Спасибо! Мы свяжемся с вами в ближайшее время.');
this.reset();
});
}
// Функция обработки отправки формы
function processFormSubmission(formData, formName) {
const data = {
form: formName,
timestamp: new Date().toLocaleString()
};
for (let [key, value] of formData.entries()) {
data[key] = value;
}
// Здесь можно добавить отправку на сервер
console.log('Данные формы:', data);
// Пример отправки в Telegram (раскомментировать и настроить)
// sendToTelegram(data);
}
// ===== МОДАЛЬНЫЕ ОКНА =====
// Открытие модального окна
document.querySelectorAll('[data-modal-open]').forEach(button => {
button.addEventListener('click', function() {
const modalId = this.getAttribute('data-modal-open');
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = 'flex';
document.body.style.overflow = 'hidden';
}
});
});
// Закрытие модального окна
document.querySelectorAll('[data-modal-close]').forEach(button => {
button.addEventListener('click', function() {
const modal = this.closest('.modal');
if (modal) {
modal.style.display = 'none';
document.body.style.overflow = 'auto';
}
});
});
// Закрытие по клику вне окна
document.querySelectorAll('.modal').forEach(modal => {
modal.addEventListener('click', function(e) {
if (e.target === this) {
this.style.display = 'none';
document.body.style.overflow = 'auto';
}
});
});
// ===== АДАПТИВНОЕ МЕНЮ =====
const mobileMenuBtn = document.getElementById('mobile-menu-btn');
const mobileMenu = document.getElementById('mobile-menu');
const mobileMenuClose = document.getElementById('mobile-menu-close');
if (mobileMenuBtn && mobileMenu) {
mobileMenuBtn.addEventListener('click', function() {
mobileMenu.classList.add('active');
document.body.style.overflow = 'hidden';
});
if (mobileMenuClose) {
mobileMenuClose.addEventListener('click', function() {
mobileMenu.classList.remove('active');
document.body.style.overflow = 'auto';
});
}
// Закрытие меню при клике на ссылку
mobileMenu.querySelectorAll('a').forEach(link => {
link.addEventListener('click', function() {
mobileMenu.classList.remove('active');
document.body.style.overflow = 'auto';
});
});
}
// ===== АНИМАЦИЯ ПРИ СКРОЛЛЕ =====
const animateOnScroll = function() {
const elements = document.querySelectorAll('.feature-item, .step-item, .advantage-item');
elements.forEach(element => {
const elementTop = element.getBoundingClientRect().top;
const elementVisible = 150;
if (elementTop < window.innerHeight - elementVisible) {
element.style.opacity = '1';
element.style.transform = 'translateY(0)';
}
});
};
// Инициализация анимации
const animatedElements = document.querySelectorAll('.feature-item, .step-item, .advantage-item');
animatedElements.forEach(element => {
element.style.opacity = '0';
element.style.transform = 'translateY(30px)';
element.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
});
window.addEventListener('scroll', animateOnScroll);
animateOnScroll(); // Инициализация при загрузке
// ===== СЧЕТЧИКИ (если нужны) =====
function animateCounter(element, target, duration) {
let start = 0;
const increment = target / (duration / 16);
const timer = setInterval(() => {
start += increment;
if (start >= target) {
element.textContent = target + '+';
clearInterval(timer);
} else {
element.textContent = Math.floor(start);
}
}, 16);
}
// Активация счетчиков при скролле
const counters = document.querySelectorAll('.counter');
let countersAnimated = false;
function checkCounters() {
const countersSection = document.querySelector('.stats-section');
if (!countersSection || countersAnimated) return;
const sectionTop = countersSection.getBoundingClientRect().top;
if (sectionTop < window.innerHeight - 100) {
counters.forEach(counter => {
const target = parseInt(counter.getAttribute('data-target'));
animateCounter(counter, target, 2000);
});
countersAnimated = true;
}
}
window.addEventListener('scroll', checkCounters);
// ===== ВАЛИДАЦИЯ ТЕЛЕФОНА =====
document.querySelectorAll('input[type="tel"]').forEach(input => {
input.addEventListener('input', function(e) {
this.value = this.value.replace(/[^\d+]/g, '');
});
});
// ===== ПОКАЗ УВЕДОМЛЕНИЙ =====
function showSuccessMessage(message) {
// Создаем элемент уведомления
const notification = document.createElement('div');
notification.className = 'success-notification';
notification.innerHTML = `
✓ ${message}
`;
document.body.appendChild(notification);
// Показываем уведомление
setTimeout(() => notification.classList.add('show'), 100);
// Убираем через 5 секунд
setTimeout(() => {
notification.classList.remove('show');
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 5000);
}
// ===== ИНИЦИАЛИЗАЦИЯ MASK ДЛЯ ТЕЛЕФОНА (если нужно) =====
// Для использования раскомментируйте и подключите библиотеку inputmask
/*
if (typeof Inputmask !== 'undefined') {
Inputmask("+7 (999) 999-99-99").mask(document.querySelectorAll('input[type="tel"]'));
}
*/
});
// ===== ОТПРАВКА В TELEGRAM (пример) =====
function sendToTelegram(data) {
const botToken = 'YOUR_BOT_TOKEN';
const chatId = 'YOUR_CHAT_ID';
const message = `
???? Новая заявка с сайта:
Форма: ${data.form}
Время: ${data.timestamp}
Имя: ${data.name || 'Не указано'}
Телефон: ${data.phone || 'Не указан'}
Email: ${data.email || 'Не указан'}
Ссылка: ${data.link || 'Не указана'}
`.trim();
fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
chat_id: chatId,
text: message,
parse_mode: 'HTML'
})
});
}
// ===== АНИМАЦИЯ ТАЙМЕРОВ ДЛЯ ПРЕИМУЩЕСТВ =====
function startCounters() {
const counters = document.querySelectorAll('[data-counter]');
counters.forEach(counter => {
const target = parseInt(counter.getAttribute('data-counter'));
const duration = 2000;
let start = 0;
const increment = target / (duration / 16);
const timer = setInterval(() => {
start += increment;
if (start >= target) {
counter.textContent = target + '+';
clearInterval(timer);
} else {
counter.textContent = Math.floor(start);
}
}, 16);
});
}
// Запуск при загрузке страницы
window.addEventListener('load', function() {
console.log('Сайт "Самовыкупы" загружен!');
});
/* styles.css - дополнение для функциональности */
/* Модальные окна */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
align-items: center;
justify-content: center;
}
.modal-content {
background: white;
padding: 2rem;
border-radius: 10px;
max-width: 500px;
width: 90%;
position: relative;
}
.modal-close {
position: absolute;
top: 1rem;
right: 1rem;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
}
/* Адаптивное меню */
.mobile-menu {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: white;
z-index: 999;
flex-direction: column;
padding: 2rem;
}
.mobile-menu.active {
display: flex;
}
.mobile-menu-close {
align-self: flex-end;
background: none;
border: none;
font-size: 1.5rem;
margin-bottom: 2rem;
cursor: pointer;
}
/* Уведомления */
.success-notification {
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 1rem 1.5rem;
border-radius: 5px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
transform: translateX(400px);
transition: transform 0.3s ease;
z-index: 1001;
}
.success-notification.show {
transform: translateX(0);
}
.notification-content {
display: flex;
align-items: center;
gap: 0.5rem;
}
.notification-icon {
font-weight: bold;
}
/* Анимации */
.feature-item, .step-item, .advantage-item {
opacity: 0;
transform: translateY(30px);
transition: opacity 0.6s ease, transform 0.6s ease;
}
/* Адаптивность */
@media (max-width: 768px) {
.modal-content {
margin: 1rem;
width: calc(100% - 2rem);
}
.success-notification {
left: 1rem;
right: 1rem;
transform: translateY(-100px);
}
.success-notification.show {
transform: translateY(0);
}
}
/* Интерактивные элементы */
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0,0,0,0.2);
transition: all 0.3s ease;
}
.form-input:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);
transition: all 0.3s ease;
}