之前個 Post 話有找條 Link 可以用來做 Ajax Search,今日有時間就做好左了。

呢個就係條 Link 個樣 : [/feeds/posts/summary?callback=callcall&max-results=50&q=react&start-index=1&alt=json&orderby=updated](/feeds/posts/summary?callback=callcall&max-results=50&q=react&start-index=1&alt=json&orderby=updated)

原本佢係用來做 RSS 的 (我估),不過佢有支援可以用 Json 輸出,除此之外仲有得 Support JsonP 添。

### 參數 (估估下)

- JsonP
	係上面條 URL 度有個 `callback` 的 params,只要你比個名佢,佢就會以 JsonP 的方適去 Response 返來。

- Json
	係上面條 URL 度有個 `alt` 的 params,填個 'json' 比佢,就會以 json 的方式 Response 返來。

- Query
	係上面條 URL 度有個 `q` 的 params,填你想要搜索的關鍵字比佢,就可以搵返相應的 Result 返來。

### 實作時遇到的事情

記錄一下在實作時遇到的事情

#### Custom Event

可以為 Dom element 加入 / 觸發自訂的事件。

```js
// select a single dom element
const element = document.querySelector('#mydiv');

// your custom event handler
element.addEventListener('yourcustomevent', function(evt) {

	console.log('hi, this is your custom event');
});

// prepare event object
const evt = new Event('yourcustomevent');

// dispatch the event.
element.dispatchEvent(evt);
```

#### 取得 Dom element (static position) 的 position (relative to window)

如果淨係用 `getBoundingClientRect()` 只可以取得未加入 window.scroll 的 (X,Y) 值,所以實際用起來時一定要加返 (window.scrollX, window.scrollY) 的值才能使用。

```js
// select a single dom element
const element = document.querySelector('#mydiv');

// get position
element.getBoundingClientRect().top + window.scrollY;
```

#### text-overflow: ellipsis; 用唔到

解決 : https://stackoverflow.com/questions/17779293/css-text-overflow-ellipsis-not-working

就係要必需設定對上一個 block element 的以下 CSS:

```css
div.text-overflow {
	overflow: hidden;
	white-space: nowrap;
}
```

#### encodeURIComponent

記得由 User input 的資料要放入去 URL 時,都一定要做好 `encodeURIComponent()` 先得。

```js
// 由使用者自己輸入
const userInputValue = 'hello world';

// 必定要做好 encodeURIComponent 才能放心
const url = `https://example.com/api/v1/users?name=${encodeURIComponent(userInputValue)}`;
```

#### 記住用 : DOMContentLoaded

呢度 : https://stackoverflow.com/questions/9899372/vanilla-javascript-equivalent-of-jquerys-ready-how-to-call-a-function-whe

如果想安全啲,記得要係呢個 event 入面先好操作 Dom elements。

以前 IE6 年代件用 `window.onload = function() { ... }`;

到到 jQuery 年度用 `$(function() { ... })`;

到翻 Vanilla Javascript 返璞歸真,用下面呢個例子 :

```html
// fire when dom content loaded
document.addEventListener('DOMContentLoaded', function(evt) {

    // Your code to run since DOM is loaded and ready
});
```

### 總結

唔寫低真係會唔記得,上面操作做過無數次,不過每次都係要 Search 下 Google 有無更好的做法。

而都係必需既,可能過幾篇文章又會再寫過呢啲一樣既野。
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)