-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
310 lines (260 loc) · 8.36 KB
/
app.js
File metadata and controls
310 lines (260 loc) · 8.36 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
/* app.js
CCA Lab: JS essentials for modern UI work
Mindset: "state drives UI" (exactly what you'll do in React/Next.js later)
*/
/* Structure
1. State: the data that represents our app's current situation
2. Data: the set of information we have regarding features, pricing, etc.
3. Helpers: functions that perform specific tasks (e.g., localStorage, utilities, updating the UI)
4. Rendering functions: functions that take the current state and data to update the UI accordingly
5. Event handlers: functions that respond to user interactions (e.g., clicks, form submissions) and update the state
6. Initialization (Boot) function: the function that sets up our app when the page loads
*/
/* 1. State */
const state = {
billing: "monthly", // "monthly" or "annual"
activeTab: "speed", // "speed", "quality" or "scale"
};
/* 2. Get the elements we need to interact with */
const menuBtn = document.getElementById("menuBtn");
const nav = document.getElementById("nav");
const tabPanel = document.getElementById("tabPanel");
const tabs = Array.from(document.querySelectorAll(".Tab"));
const billingToggle = document.getElementById("billingToggle");
const pricingCards = document.getElementById("pricingCards");
/* 3. Data for the app */
const featureCopy = {
speed: {
title: "Speed that actually matters",
body: "Less waiting, fewer clicks, cleaner UI. You’ll feel it instantly.",
points: [
"Fast layout patterns (Grid/Flex used properly)",
"No messy DOM updates all over the place",
"Clear separation: data -> render -> events",
],
},
quality: {
title: "Quality by default",
body: "Semantic HTML, accessible basics, and maintainable CSS. Not vibes-only code.",
points: [
"Structure that makes sense even without CSS",
"Reusable styles instead of copy/paste classes",
"Predictable behaviour from clean JS logic",
],
},
scale: {
title: "Scale into React/Next.js",
body: "Same idea: state drives UI, UI is a function of data.",
points: [
"State object is your single source of truth",
"Render functions are your ‘components’ today",
"Events update state, then you re-render",
],
},
};
// Pricing plans are also plain data.
// We render cards from this array.
const pricing = [
{
name: "Starter",
monthly: 0,
annual: 0,
perks: ["1 project", "Basic components", "Community"],
},
{
name: "Pro",
monthly: 12,
annual: 99,
perks: ["Unlimited projects", "Reusable UI", "Faster workflow"],
},
{
name: "Team",
monthly: 29,
annual: 249,
perks: ["Team setup", "Shared patterns", "Review checklist"],
},
];
/* 4. Helpers */
function savePref() {
// Store only what we need to remember
localStorage.setItem(
"cca_lab_pref",
JSON.stringify({
billing: state.billing,
activeTab: state.activeTab,
}),
);
}
function loadPref() {
// Read saved preferences safely
try {
const saved = JSON.parse(localStorage.getItem("cca_lab_pref"));
if (!saved) return;
if (saved.billing === "monthly" || saved.billing === "annual") {
state.billing = saved.billing;
}
if (featureCopy[saved.activeTab]) {
state.activeTab = saved.activeTab;
}
} catch {
// If something is corrupted, ignore it
}
}
// Small helper to smooth scroll to a section
function scrollToId(id) {
const el = document.getElementById(id);
if (!el) return;
el.scrollIntoView({ behavior: "smooth" });
}
/* 5. Rendering functions */
function renderNavButton(open) {
// Keep accessibility state in sync
menuBtn.setAttribute("aria-expanded", open ? "true" : "false");
}
function renderTabs() {
//Render the content based on the active tab in state
const data = featureCopy[state.activeTab];
tabPanel.innerHTML = `
<div>
<h3 style="margin:0 0 12px;">${data.title}</h3>
<p>${data.body}</p>
<ul>
${data.points.map((p) => `<li>${p}</li>`).join("")}
</ul>
</div>
`;
// Update the tab buttons style (active/inactive)
tabs.forEach((btn) => {
const isActive = btn.dataset.tab === state.activeTab;
btn.classList.toggle("is-active", isActive);
btn.setAttribute("aria-selected", isActive ? "true" : "false");
});
}
function renderBillingToggle() {
// Set the checkbox based on state
billingToggle.checked = state.billing === "annual";
}
function renderPricing() {
const isAnnual = state.billing === "annual";
// Build the cards HTML by mapping the pricing data to card markup
pricingCards.innerHTML = pricing
.map((plan) => {
const price = isAnnual ? plan.annual : plan.monthly;
const suffix = isAnnual ? "/yr" : "/mo";
return `
<article class="Card">
<h3 style="margin:0;">${plan.name}</h3>
<div class="Card__price">$${price}${suffix}</div>
<ul>
${plan.perks.map((p) => `<li>${p}</li>`).join("")}
</ul>
<!-- data-plan lets us know which plan was clicked -->
<button class="Btn Btn--primary" type="button" data-plan="${plan.name}">
Choose ${plan.name}
</button>
</article>
`;
})
.join("");
}
function renderAll() {
// One place to refresh the UI from state
renderBillingToggle();
renderTabs();
renderPricing();
}
/* 6. Event handlers */
menuBtn.addEventListener("click", () => {
const open = nav.classList.toggle("is-open");
renderNavButton(open);
});
tabs.forEach((btn) => {
btn.addEventListener("click", () => {
state.activeTab = btn.dataset.tab;
savePref();
renderTabs(); // Only re-render the tabs section, not the whole page
});
});
billingToggle.addEventListener("change", () => {
state.billing = billingToggle.checked ? "annual" : "monthly";
savePref();
renderPricing(); // Only re-render the pricing cards, not the whole page
});
pricingCards.addEventListener("click", (e) => {
const btn = e.target.closest("button[data-plan]");
if (!btn) return;
const plan = btn.dataset.plan;
// Give the user a simple prompt + move them to the form
formMsg.textContent = `Nice — you selected ${plan}. Now sign up below.`;
scrollToId("signup");
});
/* 7. Form validation (bonus) */
function setError(fieldName, message) {
const el = document.querySelector(`[data-error-for="${fieldName}"]`);
if (el) el.textContent = message || "";
}
function isValidEmail(email) {
const normalized = String(email || "").trim();
// Practical baseline check:
// - one @
// - no spaces
// - at least one dot in the domain
// - at least 2 chars after final dot
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(normalized)) return false;
// Quick guard against obvious invalid formats like "a..b@example.com"
if (normalized.includes("..")) return false;
return true;
}
function validate(values) {
let ok = true;
//validate name
if (!values.name || values.name.trim().length < 2) {
setError("name", "Please enter a valid name (at least 2 characters).");
ok = false;
} else {
setError("name");
}
//validate email
if (!isValidEmail(values.email)) {
setError("email", "Please enter a valid email address.");
ok = false;
} else {
setError("email");
}
//validate track selected
if (!values.track) {
setError("track", "Please select a track.");
ok = false;
} else {
setError("track");
}
return ok;
}
signupForm.addEventListener("submit", (e) => {
e.preventDefault();
formMsg.textContent = ""; // Clear any previous messages
const values = {
name: signupForm.name.value.trim(),
email: signupForm.email.value.trim(),
track: signupForm.track.value,
};
if (!validate(values)) return;
// If validation passes, show a success message
formMsg.textContent = `Thanks for signing up, ${values.name}! We’ll be in touch at ${values.email}.`;
signupForm.reset(); // Clear the form
});
/* 8. Current 'live' user counter (bonus) */
function startLiveUsersTicker() {
const liveUsers = document.getElementById("liveUsers");
if (!liveUsers) return;
setInterval(() => {
const current = Number(liveUsers.textContent) || 0;
const delta = Math.random() > 0.5 ? 1 : -1;
const next = Math.max(80, current + delta);
liveUsers.textContent = String(next);
}, 1500);
}
/* 9. Initialization (Boot) function */
loadPref(); // Load any saved preferences from localStorage
renderAll(); // Render the UI based on the current state
startLiveUsersTicker(); // Start the live user counter