CS104_Assignment_1/script.js
2025-09-12 14:34:29 +00:00

296 lines
11 KiB
JavaScript

// Global Tea Emporium - JavaScript Functionality
// Image Gallery Functionality
document.addEventListener('DOMContentLoaded', function() {
console.log('Gallery script loading...');
const galleryImages = [
{
src: 'images/green-tea-leaves.webp',
alt: 'Premium Green Tea Leaves',
caption: 'Premium Green Tea Leaves - Hand-picked from our finest gardens'
},
{
src: 'images/Indian Black Teas.webp',
alt: 'Indian Black Tea Selection',
caption: 'Authentic Indian Black Teas - Rich and robust flavors from Assam and Darjeeling'
},
{
src: 'images/Oolong Selections.jpg',
alt: 'Oolong Tea Collection',
caption: 'Traditional Oolong Selections - Complex flavors from Taiwan and China'
}
];
let currentImageIndex = 0;
const galleryImage = document.getElementById('gallery-image');
const galleryCaption = document.getElementById('gallery-caption');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const thumbnails = document.querySelectorAll('.thumbnail');
// Check if gallery elements exist
if (!galleryImage || !galleryCaption) {
console.log('Gallery image or caption not found');
return;
}
console.log('Gallery elements found:', {
image: !!galleryImage,
caption: !!galleryCaption,
prevBtn: !!prevBtn,
nextBtn: !!nextBtn,
thumbnails: thumbnails.length
});
function updateGallery(index) {
console.log('Updating gallery to index:', index);
currentImageIndex = index;
galleryImage.src = galleryImages[index].src;
galleryImage.alt = galleryImages[index].alt;
galleryCaption.textContent = galleryImages[index].caption;
// Update active thumbnail
thumbnails.forEach((thumb, i) => {
thumb.classList.toggle('active', i === index);
});
}
function nextImage() {
console.log('Next image clicked');
const newIndex = (currentImageIndex + 1) % galleryImages.length;
updateGallery(newIndex);
}
function prevImage() {
console.log('Previous image clicked');
const newIndex = (currentImageIndex - 1 + galleryImages.length) % galleryImages.length;
updateGallery(newIndex);
}
// Event listeners for gallery controls
if (prevBtn) {
console.log('Adding prev button listener');
prevBtn.addEventListener('click', prevImage);
} else {
console.log('Prev button not found');
}
if (nextBtn) {
console.log('Adding next button listener');
nextBtn.addEventListener('click', nextImage);
} else {
console.log('Next button not found');
}
// Thumbnail click events
thumbnails.forEach((thumbnail) => {
thumbnail.addEventListener('click', () => {
const index = parseInt(thumbnail.getAttribute('data-index'));
console.log('Thumbnail clicked, index:', index);
if (!isNaN(index)) {
updateGallery(index);
}
});
});
// Auto-advance gallery every 5 seconds
setInterval(nextImage, 5000);
console.log('Gallery initialized successfully');
}); // End of DOMContentLoaded for gallery
// Enhanced Contact Form Validation
document.addEventListener('DOMContentLoaded', function() {
const contactForm = document.querySelector('.contact-form');
if (contactForm) {
const formGroups = contactForm.querySelectorAll('.form-group');
// Real-time validation function
function validateField(field) {
const formGroup = field.closest('.form-group');
const errorSpan = formGroup.querySelector('.error-message');
let isValid = true;
let errorMessage = '';
// Remove previous validation classes
formGroup.classList.remove('error', 'success');
// Validate required fields
if (field.hasAttribute('required') && !field.value.trim()) {
isValid = false;
errorMessage = 'This field is required.';
} else if (field.type === 'email' && field.value) {
// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(field.value)) {
isValid = false;
errorMessage = 'Please enter a valid email address.';
}
} else if (field.type === 'tel' && field.value) {
// Phone validation (basic)
const phoneRegex = /^[\d\s\-\+\(\)]+$/;
if (!phoneRegex.test(field.value)) {
isValid = false;
errorMessage = 'Please enter a valid phone number.';
}
} else if (field.tagName === 'TEXTAREA' && field.value.length < 10 && field.hasAttribute('required')) {
// Message length validation
isValid = false;
errorMessage = 'Message must be at least 10 characters long.';
}
// Display validation results
if (errorSpan) {
errorSpan.textContent = errorMessage;
}
if (isValid && field.value.trim()) {
formGroup.classList.add('success');
} else if (!isValid) {
formGroup.classList.add('error');
}
return isValid;
}
// Add real-time validation to all form fields
formGroups.forEach(group => {
const input = group.querySelector('input, textarea');
if (input) {
input.addEventListener('blur', () => validateField(input));
input.addEventListener('input', () => {
if (group.classList.contains('error')) {
validateField(input);
}
});
}
});
contactForm.addEventListener('submit', function(e) {
e.preventDefault();
let isFormValid = true;
const formData = new FormData(contactForm);
const data = Object.fromEntries(formData);
// Validate all fields
formGroups.forEach(group => {
const input = group.querySelector('input, textarea');
if (input && !validateField(input)) {
isFormValid = false;
}
});
if (!isFormValid) {
// Focus on first error field
const firstError = contactForm.querySelector('.form-group.error input, .form-group.error textarea');
if (firstError) {
firstError.focus();
}
return;
}
// Simulate form submission with loading state
const submitBtn = contactForm.querySelector('.submit-btn');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Sending...';
submitBtn.disabled = true;
setTimeout(() => {
alert(`Thank you for your message, ${data.name}! We'll get back to you soon at ${data.email}.`);
contactForm.reset();
formGroups.forEach(group => group.classList.remove('error', 'success'));
submitBtn.textContent = originalText;
submitBtn.disabled = false;
}, 2000);
});
}
});
// FAQ Accordion Functionality
document.addEventListener('DOMContentLoaded', function() {
const faqQuestions = document.querySelectorAll('.faq-question');
faqQuestions.forEach(question => {
question.addEventListener('click', function() {
const answer = this.nextElementSibling;
const toggle = this.querySelector('.faq-toggle');
const isExpanded = this.getAttribute('aria-expanded') === 'true';
// Close all other FAQ items
faqQuestions.forEach(otherQuestion => {
if (otherQuestion !== this) {
const otherAnswer = otherQuestion.nextElementSibling;
const otherToggle = otherQuestion.querySelector('.faq-toggle');
otherQuestion.setAttribute('aria-expanded', 'false');
otherAnswer.classList.remove('active');
otherToggle.classList.remove('active');
}
});
// Toggle current FAQ item
this.setAttribute('aria-expanded', !isExpanded);
answer.classList.toggle('active');
toggle.classList.toggle('active');
});
// Add keyboard navigation
question.addEventListener('keydown', function(e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
this.click();
}
});
});
});
// Smooth scrolling for navigation links
document.addEventListener('DOMContentLoaded', function() {
const navLinks = document.querySelectorAll('.main-nav a');
navLinks.forEach(link => {
link.addEventListener('click', function(e) {
// Check if it's an internal link
if (this.hostname === window.location.hostname) {
// Add a subtle animation effect
this.style.transform = 'scale(0.95)';
setTimeout(() => {
this.style.transform = 'scale(1)';
}, 150);
}
});
});
});
// Add hover effects to service items
document.addEventListener('DOMContentLoaded', function() {
const serviceItems = document.querySelectorAll('.services-list li, .value-item, .timeline-item');
serviceItems.forEach(item => {
item.addEventListener('mouseenter', function() {
this.style.transform = 'translateY(-2px)';
this.style.transition = 'transform 0.3s ease';
});
item.addEventListener('mouseleave', function() {
this.style.transform = 'translateY(0)';
});
});
});
// Active navigation highlighting
document.addEventListener('DOMContentLoaded', function() {
const currentPage = window.location.pathname.split('/').pop();
const navLinks = document.querySelectorAll('.main-nav a');
navLinks.forEach(link => {
const linkPage = link.getAttribute('href');
if (linkPage === currentPage || (currentPage === '' && linkPage === 'index.html')) {
link.style.backgroundColor = '#daa520';
link.style.color = '#5d4037';
}
});
});