### Initialize UI Toggles on Load
Source: https://afoo.me/posts.html
Sets up click handlers for menu toggles and color scheme switches when the window loads. It uses the `attachEvent` utility to manage UI states and theme persistence by toggling CSS classes on elements and the body.
```javascript
window.onload = function () {
attachEvent('[data-toggle-menu]', 'click', function (elem) {
elem.classList.toggle('expanded');
document.body.classList.toggle('overflow-hidden');
document.getElementById('header')?.classList.toggle('h-screen');
document.querySelector('#header nav')?.classList.toggle('hidden');
});
attachEvent('[data-toggle-color-scheme]', 'click', function () {
document.documentElement.classList.toggle('dark');
localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
});
};
```
--------------------------------
### Theme Initialization and Toggling
Source: https://afoo.me/
Sets the default theme to 'light' if not already defined in localStorage. It then applies the 'dark' class to the document element based on localStorage or system preference, enabling dark mode.
```javascript
// Set "light" theme as default if (!localStorage.theme) { localStorage.theme = "light"; }
if ( localStorage.theme === "dark" || (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches) ) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
```
--------------------------------
### Tippy.js Tooltip Initialization
Source: https://afoo.me/posts.html
Initializes a tooltip using the Tippy.js library for an element with the ID 'aiedu'. The tooltip provides information about AI topics like LLM and Stable Diffusion, directing users to a specific URL for more details.
```javascript
tippy('#aiedu', {
content: "As to AI nowadays, LLM and Stable Diffusion are hot even hottest among them, If your want to both know-why and know-how with them, instead of only know-how which can't repeat itself, you should get you to https://ai.afoo.me right now ❗"
});
```
--------------------------------
### Gitalk Initialization
Source: https://afoo.me/books.html
JavaScript code snippet for initializing the Gitalk commenting system. It configures the client ID, secret, repository, owner, admin users, and the unique ID for comments, along with display modes.
```javascript
var gitalk = new Gitalk({
clientID: '518a605d711883414ac0',
clientSecret: '69fb8ccc0616c5bcbc64d24ece0d06d279da91ff',
repo: 'afoo.me.comments',
owner: 'fujohnwang',
admin: ['fujohnwang'],
id: location.pathname.substring(0, 49), // Ensure uniqueness and length less than 50
distractionFreeMode: false // Facebook-like distraction free mode
})
gitalk.render('comments')
```
--------------------------------
### Integrate Pagefind Search UI
Source: https://afoo.me/posts.html
Initializes the Pagefind search user interface, targeting a specific DOM element with the ID 'search'. This enables client-side search functionality provided by the Pagefind library.
```javascript
window.addEventListener('DOMContentLoaded', (event) => {
new PagefindUI({ element: '#search'});
});
```
--------------------------------
### Website Configuration and Metadata
Source: https://wfq.gumroad.com/
This JSON object contains various configuration settings for the website, including Rails environment details, locale settings, version information, host, scheme, and user agent data. It also includes design and domain settings.
```json
{"initial":null} {"railsEnv":"production","inMailer":false,"i18nLocale":"en","i18nDefaultLocale":"en","rorVersion":"14.0.4","rorPro":false,"href":"https://wfq.gumroad.com/","location":"/","scheme":"https","host":"wfq.gumroad.com","port":null,"pathname":"/","search":null,"httpAcceptLanguage":"*","design_settings":{"font":{"name":"ABC Favorit","url":"https://assets.gumroad.com/assets/ABCFavorit-Regular-26182c8c3addf6e4f8889817249c23b22c93233a8212e5e86574459e4dc926e2.woff2"}},"domain_settings":{"scheme":"https","app_domain":"gumroad.com","root_domain":"gumroad.com","short_domain":"gum.co","discover_domain":"gumroad.com","third_party_analytics_domain":"gumroad-analytics.com"},"user_agent_info":{"is_mobile":false},"logged_in_user":null,"current_seller":null,"csp_nonce":"Ybl/DPAbsQEPXBRD9+caNO+obT7EgTzmC55PneL4/fU=","locale":"en-US","serverSide":false}
```
--------------------------------
### Event Attachment and Window Load/Show Handlers
Source: https://afoo.me/books.html
JavaScript functions to attach event listeners to elements based on selectors and manage UI states on window load and page show events. Includes toggling menus, color schemes, and social sharing functionality.
```javascript
function attachEvent(selector, event, fn) {
const matches = document.querySelectorAll(selector);
if (matches && matches.length) {
matches.forEach((elem) => {
elem.addEventListener(event, () => fn(elem), false);
});
}
}
window.onload = function () {
attachEvent('\\[data-aw-toggle-menu\\]', 'click', function (elem) {
elem.classList.toggle('expanded');
document.body.classList.toggle('overflow-hidden');
document.getElementById('header')?.classList.toggle('h-screen');
document.querySelector('#header nav')?.classList.toggle('hidden');
});
attachEvent('\\[data-aw-toggle-color-scheme\\]', 'click', function () {
document.documentElement.classList.toggle('dark');
localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
});
attachEvent('\\[data-aw-social-share\\]', 'click', function (elem) {
const network = elem.getAttribute('data-aw-social-share');
const url = encodeURIComponent(elem.getAttribute('data-aw-url'));
const text = encodeURIComponent(elem.getAttribute('data-aw-text'));
let href;
switch (network) {
case 'facebook':
href = `https://www.facebook.com/fujohnwang`;
break;
case 'twitter':
href = `https://twitter.com/afoo_me`;
break;
case 'linkedin':
href = `https://www.linkedin.com/in/fuqiangwang/`;
break;
case 'mail':
href = `mailto:fujohnwang@gmail.com?subject=%22${text}%22&body=${text}%20${url}`;
break;
default:
return;
}
const newlink = document.createElement('a');
newlink.target = '_blank';
newlink.href = href;
newlink.click();
});
};
window.onpageshow = function () {
const elem = document.querySelector('\\[data-aw-toggle-menu\\]');
if (elem) {
elem.classList.remove('expanded');
}
document.body.classList.remove('overflow-hidden');
document.getElementById('header')?.classList.remove('h-screen');
document.querySelector('#header nav')?.classList.add('hidden');
};
```
--------------------------------
### 福强私学 - 产品与服务文档
Source: https://afoo.me/kb.html
此文档块概述了“福强私学”产品的核心价值、定价模型、附加权益以及常见问题解答。它详细说明了产品的目标用户、内容更新策略、购买选项(年卡、终身权益)以及用户可能遇到的技术或访问问题。
```APIDOC
Product: 福强私学 (Fuqiang Private School)
Description:
A knowledge base and growth platform offering continuously updated content across technology, architecture, management, and business.
Aims to upgrade user cognition and evolve thinking.
Key Features:
- Rich and continuously updated content.
- Price increases annually.
- Focus on knowledge and cognition upgrade.
- Evolution of technology and thinking.
- Experience in organization and management.
- Collision of business and humanity.
Pricing Tiers:
1. Annual Subscription:
- Price: ¥ 512/year
- Benefits:
- 20% discount on one-on-one paid consultations during subscription period.
- Free access to "Fu Bao Group" paid community (original price ¥500).
- Annual price increase of 11%.
2. Lifetime Access:
- Price: ¥ 199800 / Lifetime
- Benefits:
- Full access to all content and updates from 2017 until the author's "non-abrasion" date.
- 50% discount on offline classes for life.
- Free paid consultation in the first year (limited to the first 20 customers annually).
- Free access to "Fu Bao Group" paid community (original price ¥500).
3. "Fu Bao" Subscription (Higher-end Content):
- Target Audience: Entrepreneurs, senior executives, seasoned professionals.
- Content Areas: Society, organizational management, corporate equity & profit distribution, technical architecture & strategic decision-making.
- Access Note: Requires special network techniques to access; content is intentionally made difficult to access by some parties.
FAQ:
- Why create "福强私学"?
- To create a foundational platform for continuous content creation and accumulation, leaving a lasting impact.
- Why use 'kb' as a domain/product identifier?
- 'kb' stands for Knowledge Base; "福强私学" is Fuqiang's knowledge base.
- Why text-based?
- Text is more suitable for conveying logic, thought, and inspiration than emotions, though images and videos are used where appropriate (e.g., LLMs, Stable Diffusion).
- Why a document-style online website?
- Enables timely updates and immediate reading, allowing users to access the latest content and avoid outdated information.
- Troubleshooting 403 Forbidden errors:
- Potential causes:
1. Authorization stored in Cloudflare Workers KV has a ~1-minute synchronization delay.
2. Program bug or other rare issues.
- Resolution: Wait a minute and try again for delay issues; contact support via QR code for bugs.
Contact:
- For issues, scan the QR code at the bottom of the page to contact Fuqiang.
```
--------------------------------
### Form Submission Configuration
Source: https://afoo.me/books.html
API documentation for configuring a form submission service using a custom 'formbutton' function. It specifies the submission endpoint, form title, fields with their types, labels, names, requirements, and placeholders, as well as styling options.
```apidoc
/* paste this line in verbatim */
window.formbutton=window.formbutton||function(){(formbutton.q=formbutton.q||[]).push(arguments)};
/* customize formbutton below*/
formbutton("create", {
action: "https://formspree.io/f/xknlpkkd",
title: "有什么可以帮到您?💕💕💕 How can I help you?",
fields: [
{
type: "email",
label: "您的电子邮箱(方便与您联系):",
name: "email",
required: true,
placeholder: "your@email.com"
},
{
type: "textarea",
label: "您想提交的反馈和询问信息:",
name: "message",
placeholder: "What's on your mind?",
},
{
type: "submit"
}
],
styles: {
title: {
backgroundColor: "blue"
},
button: {
backgroundColor: "blue"
}
}
});
```
--------------------------------
### Theme Management Script
Source: https://afoo.me/books.html
JavaScript code to manage the website's theme (light/dark) based on user preference or system settings. It sets the 'dark' class on the document element and stores the preference in localStorage.
```javascript
// Set "light" theme as default //
if (!localStorage.theme) {
localStorage.theme = "light";
}
if ( localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) ) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
```
--------------------------------
### JavaScript: Website Theme and UI Controls
Source: https://afoo.me/consulting.html
This JavaScript code handles the default theme setting (light/dark) based on user preference or system settings. It also includes functions to attach event listeners for toggling menus, switching color schemes, and sharing content on social media networks.
```javascript
// Set "light" theme as default // if (!localStorage.theme) { // localStorage.theme = "light"; // } if ( localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) ) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } function attachEvent(selector, event, fn) { const matches = document.querySelectorAll(selector); if (matches && matches.length) { matches.forEach((elem) => { elem.addEventListener(event, () => fn(elem), false); }); } } window.onload = function () { attachEvent('[data-aw-toggle-menu]', 'click', function (elem) { elem.classList.toggle('expanded'); document.body.classList.toggle('overflow-hidden'); document.getElementById('header')?.classList.toggle('h-screen'); document.querySelector('#header nav')?.classList.toggle('hidden'); }); attachEvent('[data-aw-toggle-color-scheme]', 'click', function () { document.documentElement.classList.toggle('dark'); localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light'; }); attachEvent('[data-aw-social-share]', 'click', function (elem) { const network = elem.getAttribute('data-aw-social-share'); const url = encodeURIComponent(elem.getAttribute('data-aw-url')); const text = encodeURIComponent(elem.getAttribute('data-aw-text')); let href; switch (network) { case 'facebook': href = `https://www.facebook.com/fujohnwang`; break; case 'twitter': href = `https://twitter.com/fujohnwang`; break; case 'linkedin': href = `https://www.linkedin.com/in/fuqiangwang/`; break; case 'mail': href = `mailto:fujohnwang@gmail.com?subject=%22${text}%22&body=${text}%20${url}`; break; default: return; } const newlink = document.createElement('a'); newlink.target = '_blank'; newlink.href = href; newlink.click(); }); }; window.onpageshow = function () { const elem = document.querySelector('[data-aw-toggle-menu]'); if (elem) { elem.classList.remove('expanded'); } document.body.classList.remove('overflow-hidden'); document.getElementById('header')?.classList.remove('h-screen'); document.querySelector('#header nav')?.classList.add('hidden'); };
```
--------------------------------
### Theme Toggling and Social Share JavaScript
Source: https://afoo.me/kb.html
This JavaScript code handles client-side functionalities including toggling between light and dark themes based on user preference or system settings, managing mobile menu expansion, and facilitating social media sharing via specific data attributes. It also includes utility functions for managing referral and coupon links.
```javascript
```
--------------------------------
### Form Button Configuration
Source: https://afoo.me/posts.html
Configures a custom form submission handler using `formbutton`. This API allows defining form actions, titles, button images, input fields with types and labels, and styling options for the form interface.
```APIDOC
window.formbutton=window.formbutton||function(){(formbutton.q=formbutton.q||[]).push(arguments)};
/* customize formbutton below*/
formbutton("create", {
action: "https://formspree.io/f/xknlpkkd",
title: "有什么可以帮到您?💕💕💕 How can I help you?",
buttonImg: "
",
fields: [
{
type: "email",
label: "您的电子邮箱(方便与您联系):",
name: "email",
required: true,
placeholder: "your@email.com"
},
{
type: "textarea",
label: "您想提交的反馈和询问信息:",
name: "message",
placeholder: "What's on your mind?",
},
{
type: "submit"
}
],
styles: {
title: {
backgroundColor: "blue"
},
button: {
backgroundColor: "blue"
}
}
});
```
--------------------------------
### Theme Toggling with Local Storage
Source: https://afoo.me/posts.html
Manages website theme (light/dark) based on user preference and system settings, storing the choice in localStorage for persistence. It applies a 'dark' class to the root element if the theme is dark or if the system prefers dark mode and no theme is explicitly set.
```javascript
if (!localStorage.theme) { localStorage.theme = "light"; }
if ( localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) ) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
```
--------------------------------
### Keyboard Shortcut for Search Focus
Source: https://afoo.me/posts.html
Adds a global keydown event listener to focus the search input field when the '/' or '.' keys are pressed. This provides a quick way for users to initiate a search.
```javascript
window.addEventListener('keydown', (event) => {
if (event.key === '/' || event.key === '.') {
event.preventDefault();
document.querySelector('div#search input').focus();
}
});
```
--------------------------------
### JavaScript 订阅与重定向函数
Source: https://afoo.me/kb.html
展示了用于触发订阅流程和获取重定向 URL 的 JavaScript 函数。这些函数通常用于前端交互,以启动购买或导航流程。
```javascript
function subscribeNow() {
// Implementation to initiate subscription process
console.log("Initiating subscription...");
}
function getRedirectURL() {
// Implementation to get the redirect URL
console.log("Getting redirect URL...");
return "/some/path";
}
```
--------------------------------
### Fetch User Total API and Update DOM
Source: https://afoo.me/kb.html
Fetches the total number of users from a specified API endpoint and updates an HTML element with the result. Includes basic error logging for failed requests.
```javascript
fetch("https://afoo.me/api/users/total").then(r=> r.json()).then(j=> {
document.getElementById("userTotal").innerText = j.total
}).catch(e=> {
console.error("fails to get user total, ignore.")
})
```
--------------------------------
### JavaScript: Form Submission Integration
Source: https://afoo.me/consulting.html
This JavaScript snippet configures and integrates a form submission service using Formspree. It defines the form action URL, a custom title, a button image, and the fields required for the form, including email, message, and a submit button.
```javascript
/* paste this line in verbatim */ window.formbutton=window.formbutton||function(){(formbutton.q=formbutton.q||[]).push(arguments)}; /* customize formbutton below*/ formbutton("create", { action: "https://formspree.io/f/xknlpkkd", title: "有什么可以帮到您?💕💕💕 How can I help you?", buttonImg: "
", fields: [ { type: "email", label: "您的电子邮箱(方便与您联系):", name: "email", required: true, placeholder: "your@email.com" }, { type: "textarea", label: "您想提交的反馈和询问信息:", name: "message", placeholder: "What's on your mind?", }, { type: "submit" } ], styles: { title: { backgroundColor: "blue" }, button: { backgroundColor: "blue" } } });
```
--------------------------------
### Utility for Attaching Event Listeners
Source: https://afoo.me/
A helper function to find all elements matching a CSS selector and attach a specified event listener to each. It passes the element itself to the callback function.
```javascript
function attachEvent(selector, event, fn) {
const matches = document.querySelectorAll(selector);
if (matches && matches.length) {
matches.forEach((elem) => {
elem.addEventListener(event, () => fn(elem), false);
});
}
}
```
--------------------------------
### Gumroad Product Data Structure
Source: https://wfq.gumroad.com/
This JSON object represents product data from a Gumroad seller profile. It details product information such as title, price, thumbnail, and type, organized into sections for ebooks and video courses. The structure includes seller details, product lists with individual attributes, and associated tags.
```json
{
"currency_code": "usd",
"show_ratings_filter": true,
"creator_profile": {
"external_id": "9527565973752",
"avatar_url": "https://public-files.gumroad.com/i2g6l34da52br0n6f75p407l12en",
"name": "王福强",
"twitter_handle": "afoo_me",
"subdomain": "wfq.gumroad.com"
},
"sections": [
{
"id": "h1Qj7zbZW6ql0IoSQ5C2xQ==",
"header": "ebooks - 电子书",
"type": "SellerProfileProductsSection",
"show_filters": false,
"default_product_sort": "price_asc",
"search_results": {
"total": 8,
"tags_data": [
{
"key": "business",
"doc_count": 1
},
{
"key": "htmx",
"doc_count": 1
},
{
"key": "human",
"doc_count": 1
},
{
"key": "javascript",
"doc_count": 1
},
{
"key": "management",
"doc_count": 1
},
{
"key": "personality",
"doc_count": 1
},
{
"key": "reactive programming",
"doc_count": 1
},
{
"key": "scala",
"doc_count": 1
}
],
"filetypes_data": [
{
"key": "pdf",
"doc_count": 7
},
{
"key": "png",
"doc_count": 4
}
],
"products": [
{
"id": "ioHoiBZsUGk1DXgnAKLwcw==",
"permalink": "ksorp",
"name": "坑获2",
"seller": null,
"ratings": {
"count": 0,
"average": 0.0
},
"thumbnail_url": "https://public-files.gumroad.com/gragsy19sqlg11n2vpx287x12e53",
"native_type": "digital",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 500,
"currency_code": "usd",
"is_pay_what_you_want": true,
"url": "https://wfq.gumroad.com/l/kenghuo2?layout=profile",
"duration_in_months": null,
"recurrence": null
},
{
"id": "zq-P16Q2e-lyq7BBQ04xmg==",
"permalink": "mbikb",
"name": "HTMX揭秘(Unveil HTMX)",
"seller": null,
"ratings": {
"count": 0,
"average": 0.0
},
"thumbnail_url": "https://public-files.gumroad.com/p9e6zia7x8vv19h263wh4zylu6bv",
"native_type": "ebook",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 500,
"currency_code": "usd",
"is_pay_what_you_want": true,
"url": "https://wfq.gumroad.com/l/htmx?layout=profile",
"duration_in_months": null,
"recurrence": null
},
{
"id": "SBGrE5K_DHMZ41RvXMz5Ew==",
"permalink": "rdlgl",
"name": "技术、商业与人(II)",
"seller": null,
"ratings": null,
"thumbnail_url": "https://public-files.gumroad.com/a43wm5wjcwdjp38iggxjhfc8gtcl",
"native_type": "ebook",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 1024,
"currency_code": "usd",
"is_pay_what_you_want": false,
"url": "https://wfq.gumroad.com/l/tek_biz_h_2?layout=profile",
"duration_in_months": null,
"recurrence": null
},
{
"id": "4S3BpC59hzEAo4VOjxKulg==",
"permalink": "lgiije",
"name": "Simple Svelte: A frontend book from a backend developer",
"seller": null,
"ratings": {
"count": 2,
"average": 3.5
},
"thumbnail_url": "https://public-files.gumroad.com/249wdugcab946x08m0v53zldc47r",
"native_type": "digital",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 1024,
"currency_code": "usd",
"is_pay_what_you_want": true,
"url": "https://wfq.gumroad.com/l/simple_svelte?layout=profile",
"duration_in_months": null,
"recurrence": null
},
{
"id": "RZCYGHAgH-1Y0T2YvTEqgg==",
"permalink": "fANOaE",
"name": "《福强老师的极简管理课》",
"seller": null,
"ratings": {
"count": 0,
"average": 0.0
},
"thumbnail_url": "https://public-files.gumroad.com/112r8y9sit0fx4ud0b6zsd11iafc",
"native_type": "digital",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 1024,
"currency_code": "usd",
"is_pay_what_you_want": false,
"url": "https://wfq.gumroad.com/l/simple_mgt?layout=profile",
"duration_in_months": null,
"recurrence": null
},
{
"id": "BPP7_A9-FC3u5AT1sNCXmQ==",
"permalink": "uLPkW",
"name": "《技术、商业与人》",
"seller": null,
"ratings": {
"count": 0,
"average": 0.0
},
"thumbnail_url": "https://public-files.gumroad.com/1k7ecu2u7qjnshgy2hclxa2e78ck",
"native_type": "digital",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 1024,
"currency_code": "usd",
"is_pay_what_you_want": false,
"url": "https://wfq.gumroad.com/l/tek_biz_hb?layout=profile",
"duration_in_months": null,
"recurrence": null
},
{
"id": "nFRV1P9ugo7oGfB3_sxhnw==",
"permalink": "BRmvgb",
"name": "《深度思考揭秘》",
"seller": null,
"ratings": {
"count": 0,
"average": 0.0
},
"thumbnail_url": "https://public-files.gumroad.com/1crc7ubf9nk7p351x2qesqixd5p9",
"native_type": "digital",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 1024,
"currency_code": "usd",
"is_pay_what_you_want": false,
"url": "https://wfq.gumroad.com/l/way_of_deep_thinking?layout=profile",
"duration_in_months": null,
"recurrence": null
},
{
"id": "QnzR3E1oSlVyLUXa2shydQ==",
"permalink": "zyfdq",
"name": "坑获",
"seller": null,
"ratings": {
"count": 0,
"average": 0.0
},
"thumbnail_url": "https://public-files.gumroad.com/j060yvoa9qlpoyp3u5k1m54eid4k",
"native_type": "digital",
"quantity_remaining": null,
"is_sales_limited": false,
"price_cents": 1999,
"currency_code": "usd",
"is_pay_what_you_want": true,
"url": "https://wfq.gumroad.com/l/kenghuo?layout=profile",
"duration_in_months": null,
"recurrence": null
}
]
}
},
{
"id": "d-AANYpZaldYV5SaUGN58g==",
"header": "Video Courses - 视频课",
"type": "SellerProfileProductsSection",
"show_filters": false,
"default_product_sort": "page_layout",
"search_results": {
"total": 8,
"tags_data": [
{
"key": "ai",
"doc_count": 1
}
]
}
}
]
}
```
--------------------------------
### UI Event Handling on Load
Source: https://afoo.me/
Attaches click event listeners to elements with specific data attributes for menu toggling, color scheme switching, and social sharing. It manipulates DOM classes and navigates to social media platforms.
```javascript
window.onload = function () {
attachEvent("[data-toggle-menu]", "click", function (elem) {
elem.classList.toggle("expanded");
document.body.classList.toggle("overflow-hidden");
document
.getElementById("header")
?.classList.toggle("h-screen");
document.querySelector("#header nav")?.classList.toggle("hidden");
});
attachEvent("[data-toggle-color-scheme]", "click", function () {
document.documentElement.classList.toggle("dark");
localStorage.theme = document.documentElement.classList.contains("dark") ? "dark" : "light";
});
attachEvent("[data-social-share]", "click", function (elem) {
const network = elem.getAttribute("data-social-share");
const url = encodeURIComponent(
elem.getAttribute("data-url")
);
const text = encodeURIComponent(elem.getAttribute("data-text"));
let href;
switch (network) {
case "facebook":
href = `https://www.facebook.com/fujohnwang`;
break;
case "twitter":
href = `https://twitter.com/afoo_me`;
break;
case "linkedin":
href = `https://www.linkedin.com/in/fuqiangwang/`;
break;
case "mail":
href = `mailto:fujohnwang@gmail.com?subject=%22${text}%22&body=${text}%20${url}`;
break;
default:
return;
}
const newlink = document.createElement("a");
newlink.target = "_blank";
newlink.href = href;
newlink.click();
});
};
```
--------------------------------
### Attach Event Listener Utility
Source: https://afoo.me/posts.html
A helper function to attach event listeners to multiple elements matching a CSS selector. It finds all elements, iterates through them, and applies the specified event listener with a callback function that receives the element.
```javascript
function attachEvent(selector, event, fn) {
const matches = document.querySelectorAll(selector);
if (matches && matches.length) {
matches.forEach((elem) => {
elem.addEventListener(event, () => fn(elem), false);
});
}
}
```
--------------------------------
### CSS Styling for Merriweather Font and Theme Variables
Source: https://wfq.gumroad.com/
This snippet defines CSS rules for importing the Merriweather font and sets up CSS variables for theme customization, including accent colors, fonts, and background colors. It applies these styles to the body element.
```css
@import url(https://fonts.googleapis.com/css2?family=Merriweather:wght@400;600&display=swap);:root{--accent: 54 169 174;--contrast-accent: 255 255 255;--font-family: "Merriweather", "ABC Favorit", serif;--color: 0 0 0;--primary: var(--color);--contrast-primary: 255 255 255;--filled: 255 255 255;--contrast-filled: var(--color);--body-bg: #ffffff;--active-bg: rgb(var(--color) / var(--gray-1));--border-alpha: 1}body{background-color:#ffffff;color:#000;font-family:"Merriweather", "ABC Favorit", serif}
```
--------------------------------
### UI State Reset on Page Show
Source: https://afoo.me/
Resets UI states when the page is shown, such as removing 'expanded' classes from menus and resetting body/header classes related to layout and overflow, ensuring a clean state after navigation.
```javascript
window.onpageshow = function () {
const elem = document.querySelector("[data-toggle-menu]");
if (elem) {
elem.classList.remove("expanded");
}
document.body.classList.remove("overflow-hidden");
document.getElementById("header")?.classList.remove("h-screen");
document.querySelector("#header nav")?.classList.add("hidden");
};
```
--------------------------------
### Reset UI State on Page Show
Source: https://afoo.me/posts.html
Resets UI elements like menu toggles and body classes when the page is shown (e.g., after back/forward navigation). This ensures a clean state by removing specific classes that indicate an expanded menu or hidden body overflow.
```javascript
window.onpageshow = function () {
const elem = document.querySelector('[data-toggle-menu]');
if (elem) {
elem.classList.remove('expanded');
}
document.body.classList.remove('overflow-hidden');
document.getElementById('header')?.classList.remove('h-screen');
document.querySelector('#header nav')?.classList.add('hidden');
};
```
--------------------------------
### Process Custom JSON Data and Update DOM
Source: https://afoo.me/kb.html
Parses a JSON string to extract 'wc' and 'ts' values. If both values are present, it updates specific DOM elements and makes a container element visible. This snippet assumes the JSON is provided as a string argument 't'.
```javascript
let json = JSON.parse(t)
const wc = json.wc
const ts = json.ts
if(wc && ts) {
document.getElementById("ma-bar-wc").innerText = wc
document.getElementById("ma-bar-ts").innerText = ts
document.getElementById("ma-bar").classList.remove("hidden")
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.