-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
81 lines (74 loc) · 2.44 KB
/
script.js
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
async function fetchAndRender(url, containerId, renderItem) {
try {
const response = await fetch(url);
const data = await response.json();
const container = document.getElementById(containerId);
if (container) {
data.forEach((item) => {
const element = renderItem(item);
container.appendChild(element);
});
}
} catch (error) {
console.error("Error fetching data:", error);
}
}
function renderItem(item) {
const element = document.createElement("article");
let altText = item.title;
if (item.topic) {
altText += ` - ${item.topic}`;
} else if (item.description) {
altText += ` - ${item.description}`;
}
const image = item.image
? `<img src="${item.image}" alt="${altText}" class="item-image" onerror="this.src='https://placehold.co/100';">`
: `<img src="https://placehold.co/100" alt="Placeholder Image" class="item-image">`;
element.innerHTML = `
<h3>${item.title}</h3>
${image}
<p>${item.content || item.description}</p>
`;
return element;
}
function setTheme(theme) {
document.body.classList.toggle("dark", theme === "dark");
}
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
document.addEventListener("DOMContentLoaded", () => {
const path = window.location.pathname;
if (path.includes("projects.html")) {
fetchAndRender("projects.json", "projects-container", renderItem);
} else if (path.includes("blog.html")) {
fetchAndRender("blog.json", "blog-posts", renderItem);
}
const themeSelector = document.querySelector(".theme-selector");
const storedTheme =
localStorage.getItem("theme") ||
(window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light");
setTheme(storedTheme);
if (themeSelector) {
themeSelector.value = storedTheme;
themeSelector.addEventListener("change", (event) => {
const theme = event.target.value;
setTheme(theme);
localStorage.setItem("theme", theme);
});
}
const footer = document.querySelector("footer");
if (footer) {
const scrollTopButton = document.createElement("button");
scrollTopButton.innerHTML = '<i data-feather="arrow-up"></i>';
scrollTopButton.classList.add("scroll-top-button");
scrollTopButton.addEventListener("click", scrollToTop);
footer.appendChild(scrollTopButton);
feather.replace();
}
});