@@ -35,3 +35,68 @@ window.addEventListener('scroll', activateNav);
3535window . addEventListener ( 'load' , activateNav ) ;
3636
3737document . getElementById ( 'year' ) . textContent = new Date ( ) . getFullYear ( ) ;
38+
39+ const contactForm = document . getElementById ( 'contact-form' ) ;
40+ const formStatus = document . getElementById ( 'form-status' ) ;
41+ const humanCheckLabel = document . getElementById ( 'human-check-label' ) ;
42+ const humanCheckQuestion = document . getElementById ( 'human-check-question' ) ;
43+ const humanCheckInput = document . getElementById ( 'human-check-input' ) ;
44+ const formStartedAt = document . getElementById ( 'form-started-at' ) ;
45+
46+ const createHumanCheck = ( ) => {
47+ const a = Math . floor ( Math . random ( ) * 8 ) + 1 ;
48+ const b = Math . floor ( Math . random ( ) * 8 ) + 1 ;
49+ humanCheckQuestion . textContent = `Human check: What is ${ a } + ${ b } ?` ;
50+ humanCheckLabel . dataset . answer = String ( a + b ) ;
51+ } ;
52+
53+ if ( contactForm && formStatus && humanCheckLabel && humanCheckQuestion && humanCheckInput && formStartedAt ) {
54+ formStartedAt . value = String ( Date . now ( ) ) ;
55+ createHumanCheck ( ) ;
56+
57+ contactForm . addEventListener ( 'submit' , async ( event ) => {
58+ event . preventDefault ( ) ;
59+ formStatus . textContent = '' ;
60+
61+ if ( ! contactForm . checkValidity ( ) ) {
62+ formStatus . textContent = 'Please complete all required fields.' ;
63+ contactForm . reportValidity ( ) ;
64+ return ;
65+ }
66+
67+ const elapsed = Date . now ( ) - Number ( formStartedAt . value ) ;
68+ if ( elapsed < 4000 ) {
69+ formStatus . textContent = 'Please wait a few seconds and try again.' ;
70+ return ;
71+ }
72+
73+ if ( humanCheckInput . value . trim ( ) !== humanCheckLabel . dataset . answer ) {
74+ formStatus . textContent = 'Human check answer is incorrect.' ;
75+ createHumanCheck ( ) ;
76+ humanCheckInput . value = '' ;
77+ return ;
78+ }
79+
80+ const formData = new FormData ( contactForm ) ;
81+ const endpoint = 'https://formsubmit.co/ajax/f.shafi@queensu.ca' ;
82+
83+ try {
84+ const response = await fetch ( endpoint , {
85+ method : 'POST' ,
86+ headers : { Accept : 'application/json' } ,
87+ body : formData ,
88+ } ) ;
89+
90+ if ( ! response . ok ) {
91+ throw new Error ( 'Request failed' ) ;
92+ }
93+
94+ formStatus . textContent = 'Thanks! Your message has been sent.' ;
95+ contactForm . reset ( ) ;
96+ createHumanCheck ( ) ;
97+ formStartedAt . value = String ( Date . now ( ) ) ;
98+ } catch {
99+ formStatus . textContent = 'Could not send right now. Please email me directly at f.shafi@queensu.ca.' ;
100+ }
101+ } ) ;
102+ }
0 commit comments