-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
461 lines (385 loc) · 15 KB
/
script.js
File metadata and controls
461 lines (385 loc) · 15 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
/**
* Portfolio Website JavaScript
* Enhanced interactivity for portfolio sections, form validation, and user experience
*
* Note: This file works in conjunction with js/main.js
* Main.js handles basic functionality, this file adds enhanced features
*/
// Wait for DOM to be fully loaded and main.js to initialize
document.addEventListener('DOMContentLoaded', function() {
console.log('Enhanced Portfolio JavaScript loaded successfully');
// Small delay to ensure main.js has initialized
setTimeout(() => {
// Initialize all enhanced functionality
initializeProjectFilters();
initializeLightbox();
initializeFormValidation();
initializeCurrentYear();
initializeScrollEffects();
console.log('All enhanced JavaScript functionality initialized');
}, 100);
});
/**
* Step 4: Portfolio Sections - Project Filters
*/
function initializeProjectFilters() {
const projectsGrid = document.querySelector('.projects-grid');
if (!projectsGrid) {
console.warn('Projects grid not found');
return;
}
// Check if filters already exist to prevent duplication
if (document.querySelector('.project-filters')) {
console.log('Project filters already exist, skipping initialization');
return;
}
// Create filter buttons
const filterContainer = document.createElement('div');
filterContainer.className = 'project-filters';
filterContainer.innerHTML = `
<div class="filter-buttons">
<button class="filter-btn active" data-filter="all">All Projects</button>
<button class="filter-btn" data-filter="frontend">Frontend</button>
<button class="filter-btn" data-filter="backend">Backend</button>
<button class="filter-btn" data-filter="fullstack">Full Stack</button>
</div>
`;
// Insert filter buttons before projects grid
projectsGrid.parentNode.insertBefore(filterContainer, projectsGrid);
// Add filter functionality
const filterButtons = filterContainer.querySelectorAll('.filter-btn');
const projectCards = projectsGrid.querySelectorAll('.project-card');
function filterProjects(category) {
console.log(`Filtering projects by: ${category}`);
// Update active button
filterButtons.forEach(btn => btn.classList.remove('active'));
event.target.classList.add('active');
// Filter projects
projectCards.forEach(card => {
const projectType = card.getAttribute('data-category') || 'fullstack';
if (category === 'all' || projectType === category) {
card.style.display = 'block';
card.style.animation = 'fadeIn 0.5s ease-in-out';
} else {
card.style.display = 'none';
}
});
}
// Add click events to filter buttons
filterButtons.forEach(button => {
button.addEventListener('click', (e) => {
const filter = e.target.getAttribute('data-filter');
filterProjects(filter);
});
});
console.log('Project filters initialized');
}
/**
* Step 4: Portfolio Sections - Lightbox Effect
*/
function initializeLightbox() {
const projectImages = document.querySelectorAll('.project-image img');
if (projectImages.length === 0) {
console.warn('No project images found for lightbox');
return;
}
// Check if lightbox already exists to prevent duplication
if (document.querySelector('.lightbox')) {
console.log('Lightbox already exists, skipping initialization');
return;
}
// Create lightbox modal
const lightbox = document.createElement('div');
lightbox.className = 'lightbox';
lightbox.innerHTML = `
<div class="lightbox-content">
<span class="lightbox-close">×</span>
<img class="lightbox-image" src="" alt="">
<div class="lightbox-caption"></div>
</div>
`;
document.body.appendChild(lightbox);
function openLightbox(imageSrc, caption) {
const lightboxImage = lightbox.querySelector('.lightbox-image');
const lightboxCaption = lightbox.querySelector('.lightbox-caption');
lightboxImage.src = imageSrc;
lightboxCaption.textContent = caption || '';
lightbox.style.display = 'flex';
document.body.style.overflow = 'hidden';
console.log('Lightbox opened for:', imageSrc);
}
function closeLightbox() {
lightbox.style.display = 'none';
document.body.style.overflow = '';
console.log('Lightbox closed');
}
// Add click events to project images
projectImages.forEach(img => {
img.addEventListener('click', () => {
const imageSrc = img.src;
const caption = img.alt || 'Project Image';
openLightbox(imageSrc, caption);
});
});
// Close lightbox events
lightbox.querySelector('.lightbox-close').addEventListener('click', closeLightbox);
lightbox.addEventListener('click', (e) => {
if (e.target === lightbox) {
closeLightbox();
}
});
// Close on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && lightbox.style.display === 'flex') {
closeLightbox();
}
});
console.log('Lightbox functionality initialized');
}
/**
* Step 5: Form Validation
*/
function initializeFormValidation() {
const contactForm = document.getElementById('contact-form');
if (!contactForm) {
console.warn('Contact form not found');
return;
}
// Check if validation is already initialized
if (contactForm.dataset.validationInitialized) {
console.log('Form validation already initialized');
return;
}
const formFields = {
name: {
element: document.getElementById('name'),
required: true,
minLength: 2,
pattern: /^[a-zA-Z\s]+$/
},
email: {
element: document.getElementById('email'),
required: true,
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
},
subject: {
element: document.getElementById('subject'),
required: true,
minLength: 5
},
message: {
element: document.getElementById('message'),
required: true,
minLength: 10
}
};
// Real-time validation
Object.keys(formFields).forEach(fieldName => {
const field = formFields[fieldName];
const element = field.element;
if (!element) return;
element.addEventListener('blur', () => validateField(fieldName, field));
element.addEventListener('input', () => clearFieldError(fieldName));
});
function validateField(fieldName, fieldConfig) {
const element = fieldConfig.element;
const value = element.value.trim();
let isValid = true;
let errorMessage = '';
// Required field validation
if (fieldConfig.required && !value) {
isValid = false;
errorMessage = `${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)} is required`;
}
// Minimum length validation
if (isValid && fieldConfig.minLength && value.length < fieldConfig.minLength) {
isValid = false;
errorMessage = `${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)} must be at least ${fieldConfig.minLength} characters`;
}
// Pattern validation
if (isValid && fieldConfig.pattern && !fieldConfig.pattern.test(value)) {
isValid = false;
if (fieldName === 'email') {
errorMessage = 'Please enter a valid email address';
} else if (fieldName === 'name') {
errorMessage = 'Name can only contain letters and spaces';
}
}
// Display error or success
if (!isValid) {
showFieldError(fieldName, errorMessage);
} else {
showFieldSuccess(fieldName);
}
return isValid;
}
function showFieldError(fieldName, message) {
const element = formFields[fieldName].element;
const formGroup = element.closest('.form-group');
// Remove existing error
clearFieldError(fieldName);
// Add error styling
element.classList.add('error');
formGroup.classList.add('has-error');
// Create error message
const errorDiv = document.createElement('div');
errorDiv.className = 'field-error';
errorDiv.textContent = message;
formGroup.appendChild(errorDiv);
console.log(`Field validation error: ${fieldName} - ${message}`);
}
function showFieldSuccess(fieldName) {
const element = formFields[fieldName].element;
const formGroup = element.closest('.form-group');
element.classList.remove('error');
element.classList.add('success');
formGroup.classList.remove('has-error');
formGroup.classList.add('has-success');
console.log(`Field validation success: ${fieldName}`);
}
function clearFieldError(fieldName) {
const element = formFields[fieldName].element;
const formGroup = element.closest('.form-group');
const errorDiv = formGroup.querySelector('.field-error');
if (errorDiv) {
errorDiv.remove();
}
element.classList.remove('error');
formGroup.classList.remove('has-error');
}
// Form submission
contactForm.addEventListener('submit', function(e) {
e.preventDefault();
console.log('Form submission attempted');
// Validate all fields
let isFormValid = true;
Object.keys(formFields).forEach(fieldName => {
const field = formFields[fieldName];
if (!validateField(fieldName, field)) {
isFormValid = false;
}
});
if (isFormValid) {
// Simulate form submission
const submitButton = contactForm.querySelector('button[type="submit"]');
const originalText = submitButton.textContent;
submitButton.textContent = 'Sending...';
submitButton.disabled = true;
// Simulate API call
setTimeout(() => {
showFormSuccess();
contactForm.reset();
submitButton.textContent = originalText;
submitButton.disabled = false;
// Clear all success states
Object.keys(formFields).forEach(fieldName => {
const element = formFields[fieldName].element;
const formGroup = element.closest('.form-group');
element.classList.remove('success');
formGroup.classList.remove('has-success');
});
console.log('Form submitted successfully');
}, 2000);
} else {
console.log('Form validation failed');
}
});
function showFormSuccess() {
const successMessage = document.createElement('div');
successMessage.className = 'form-success';
successMessage.innerHTML = `
<div class="success-content">
<h3>Message Sent Successfully!</h3>
<p>Thank you for your message. I'll get back to you as soon as possible.</p>
</div>
`;
contactForm.appendChild(successMessage);
// Remove success message after 5 seconds
setTimeout(() => {
successMessage.remove();
}, 5000);
}
// Mark as initialized to prevent duplicate initialization
contactForm.dataset.validationInitialized = 'true';
console.log('Form validation initialized');
}
/**
* Step 6: Additional Features - Current Year
*/
function initializeCurrentYear() {
const currentYearElement = document.getElementById('current-year');
if (currentYearElement) {
currentYearElement.textContent = new Date().getFullYear();
console.log('Current year updated');
}
}
/**
* Step 6: Additional Features - Scroll Effects
*/
function initializeScrollEffects() {
// Header scroll effect (only if not already handled by main.js)
const header = document.querySelector('.main-header');
if (header && !header.dataset.scrollEffectsInitialized) {
window.addEventListener('scroll', () => {
if (window.pageYOffset > 100) {
header.classList.add('scrolled');
} else {
header.classList.remove('scrolled');
}
});
header.dataset.scrollEffectsInitialized = 'true';
}
// Intersection Observer for animations
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate-in');
console.log('Element animated in:', entry.target);
}
});
}, observerOptions);
// Observe elements for animation
const animateElements = document.querySelectorAll('.project-card, .skills-category, .contact-container');
animateElements.forEach(el => observer.observe(el));
console.log('Scroll effects initialized');
}
/**
* Utility Functions
*/
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Export functions for testing (if needed)
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
initializeProjectFilters,
initializeLightbox,
initializeFormValidation,
initializeCurrentYear,
initializeScrollEffects
};
}