codecraft-portfolio / script.js
momo2050's picture
You are a professional web developer and UI/UX designer.
8790072 verified
Raw
History Blame Contribute Delete
3.74 kB
document.addEventListener('DOMContentLoaded', function() {
// Smooth scrolling for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const targetId = this.getAttribute('href');
if (targetId === '#') return;
const targetElement = document.querySelector(targetId);
if (targetElement) {
window.scrollTo({
top: targetElement.offsetTop - 80,
behavior: 'smooth'
});
// Update URL without jumping
history.pushState(null, null, targetId);
}
});
});
// Highlight active nav link on scroll
const sections = document.querySelectorAll('section');
const navLinks = document.querySelectorAll('.nav-link');
window.addEventListener('scroll', () => {
let current = '';
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= (sectionTop - 100)) {
current = section.getAttribute('id');
}
});
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === `#${current}`) {
link.classList.add('active');
}
});
});
// Add animation to elements when they come into view
const animateOnScroll = () => {
const elements = document.querySelectorAll('.animate-on-scroll');
elements.forEach(element => {
const elementPosition = element.getBoundingClientRect().top;
const windowHeight = window.innerHeight;
if (elementPosition < windowHeight - 100) {
element.classList.add('animate-in');
}
});
};
// Run once on page load
animateOnScroll();
// Then run on scroll
window.addEventListener('scroll', animateOnScroll);
// Theme switcher functionality
const themeToggle = document.getElementById('theme-toggle');
if (themeToggle) {
themeToggle.addEventListener('click', () => {
document.documentElement.classList.toggle('dark');
localStorage.setItem('darkMode', document.documentElement.classList.contains('dark'));
});
}
// Check for saved theme preference
if (localStorage.getItem('darkMode') === 'true') {
document.documentElement.classList.add('dark');
} else if (localStorage.getItem('darkMode') === 'false') {
document.documentElement.classList.remove('dark');
}
// Form submission handler
const contactForm = document.querySelector('#contact form');
if (contactForm) {
contactForm.addEventListener('submit', function(e) {
e.preventDefault();
// Simple form validation
const name = this.querySelector('#name').value;
const email = this.querySelector('#email').value;
const message = this.querySelector('#message').value;
if (!name || !email || !message) {
alert('Please fill in all fields');
return;
}
// Here you would typically send the form data to a server
console.log('Form submitted:', { name, email, message });
alert('Thank you for your message! I will get back to you soon.');
this.reset();
});
}
});