---
title: JavaScript_Web_Interaction
tags: Web Directory, JavaScript, BOM, DOM, Web APIS, AJAX
description: JavaScript Notes
---
{%hackmd U6g0skbVTIyVdJhvWCgo2Q %}
# <span class="big-title">BOM</span> <span style="vertical-align: sub; font-size: 10px">Browser Object Model</span>
- `window` object
- representing browser window
- Including:
- global funciton -> method of `window`
- global variable, objects -> members of `window`
- Properties
1. `Document`
- readonly access **Document** object
2. `history`
- readonly access **History** object
4. `location`
- access **Location** object
5. `name`
- set/get name of window
## <span class="intext-title">History</span>
```htmlembedded=
<a href="javascript:window.history.forward()">forward</a>
<a href="javascript:window.history.back()">backward</a>
<a href="javascript:history.go(1)">go(1) = forward</a>
<a href="javascript:history.go(-1)">go(-1) = backward</a>
```
- can only use history when invoking methods.
## <span class="intext-title">Location</span>
```htmlembedded=
<a href="javascript:alert(window.location.href)">now URL</a>
<a href="javascript:window.location.reload()">reload page</a><br />
<a href="javascript:window.location.replace('index.html')">jump to index</a><br />
<a href="javascript:location.replace('https://www.google.com')">jump to google</a><br />
```
- `href`
- gain now url
- `reload()`
- reload page
- `replace(url)`
- replace current URL with specific URL
## <span class="intext-title">Method</span>
1. Dialog
| name | description |
| -------- | -------- |
|alert(\<meg>) |alert dialog with a confirm message|
|comfirm(\<meg>)|with confirm and cancel button |
| prompt(\<meg>, \<default>) |Have a text box which can transport message|
- Example
```javascript=
var res = window.confirm("Are you sure?");
var age = window.prompt("How old are you?");
```
2. operate browser
- `open()`
1. new window (no argument)
2. URL
3. open file with browser
- `close()`
- close browser
3. timer
```javascript=
flag2 = window.setTimeout("showTime2()",1000);
window.clearTimeout(flag2)
```
- `setInterval`, `clearInterval`
- `setTimeout`, `clearTimeout`
- difference
- Timeout will only execute once, while timeInterval will loop execute
- MIND question about single thread and event queue
## Example: `setInterval()`
- We should pass a **function** to the first argument of `setInterval`
```javascript=
let string = "Hello";
var now_index = 0;
go_str = () => {
document.getElementById("hello").innerHTML += string.charAt(now_index);
now_index ++;
if (now_index >= string.length){
now_index = 0;
}
}
setInterval(() => go_str(), 1000);
// or
setInterval(go_str, 1000);
```
> this example use arrow funciton to pass function to `setInterval()`
>> also, we can pass reference of the function to it
# <span class="big-title">DOM</span> <span style="vertical-align: sub; font-size: 10px"> Document Object Model</span>
```
Document Object Model
```

> Parse like a Tree
> Nodes: `HTMLElement`, `Attrbutes`, `Text`
## <span class="intext-title">Modify Document</span>
```htmlembedded=
<!--tag: p-->
<p name="OOInput" id="pwdIn" class="label">I am a Label</p>
```
- Document -> `window.document`
- Find
- `document.getElementById()`
- `document.getElementsByClassName()`
- `document.getElementsByTagName()`
- `document.getElementsByName()`
### <span class="intext-point">Modify Contents, Properties and CSS</span>
- Contents
- `HTMLElement.innerHTML`
- Attrbutes
```javascript=
// Way 1
document.getElementById(id).attribute=newValue;
// Way2
document.getElementById(id).setAttribute(newValue);
```
- CSS
- `HTMLElement.style`
```javascript=
document.getElementById("myli").style.color="blue";
document.getElementById("myli").style.fontSize="24px";
```
## <span class="intext-title">Modify DOM Element (Nodes)</span>
```htmlembedded=
<!DOCTYPE html>
<html>
<head>
<title>Use DOm</title>
<meta charset="UTF-8">
<script>
// Append Child
function createNewP(){
var newElementP=document.createElement("p");
var text=document.createTextNode("New P1");
var attrs=document.createAttribute("name");
attrs.value="Hello JS";
newElementP.setAttributeNode(attrs);
newElementP.appendChild(text);
var div=document.getElementById("p1");
div.appendChild(newElementP);
}
// Insert Before
function createNewP2(){
var newElementP=document.createElement("p");
var text=document.createTextNode("New P2");
newElementP.appendChild(text);
var div=document.getElementById("div1");
var p1=document.getElementById("p1");
div.insertBefore(newElementP,p1);
}
// remove element
function deleteElement(){
var div=document.getElementById("div1");
var p1=document.getElementById("p1");
div.removeChild(p1);
}
// replace element
function replaceElement(){
var p1=document.getElementById("p1");
var p1Parent=p1.parentNode;
p1Parent.removeChild(p1);
}
</script>
</head>
<body>
<button type="button" onclick="createNewP()">appendChild</button>
<button type="button" onclick="createNewP2()">insertBefore</button>
<div id="div1">
<p id="p1">PO1</p>
<p id="p2">PO2</p>
</div>
</body>
</html>
```
### <span class="intext-point">Create New HTMLElement</span>
1. create new HTMLElement
2. create child of the new HTMLElement
- `createTextNode()`
- [`createAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute)
3. Append new child to new HTML Element
- `appendChildren` for textNode
- `setAttributeNode` for attribute
4. Append new element to existed element
- `HTMLElement.appendChild()`
- `HTMLElement.insertBefore()`
### <span class="intext-point">Replacement and Deletion</span>
- From **Parent Node** -> `HTMLElement.parentNode`
- `replaceChild(<target>, <reaplaced>);`
- `removeChild(<target>);`
# <span class="big-title">Event Handling</span>
- Event, which will be triggered by HTML element
- add JS as event handler on HTML script is helpful
- Common Events
- `onchange`, `onload`
- element change, load up
- `onclick`
- `onmouseover`, `onmouseout`
- mouse in and out
- `onkeydown`
- `onfocus`, `onblur`
## <span class="intext-title">Example</span>
```htmlembedded=
<body onload="myLoad()">
<input id="userName" onkeydown="fun5()" onfocus="fun6()" onblur="fun7()"/>
<input id="password" type="password" />
<button id="btn" type="button" onclick="fun2()"
onmouseover="fun3()" onmouseout="fun4()">Touch me</button>
<select id="month" onchange="fun1()">
<option>January</option>
<option>Febunary</option>
</select>
</body>
```
# <span class="big-title">AJAX </span><span style="vertical-align: sub; font-size: 10px">Asynchronous JavaScript and XML</span>
- It have no direct dependencies with XML
- It represents the data translatted from server side.
- `asynchronous` means it can be worked like `background`
- binding callback/react function, trggered with specific request status
- It's an perspective with several component conbined
- asynchronous data translation between XHR and web server
- Dynamic changing view with JS/CSS/HTML/DOM/Framework
## <span class="intext-title">XMLHttpRequest</span>
```javascript=
// build XHR object
var httpRequest = new XMLHttpRequest();
// Before IE7
var httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
```
## <span class="intext-title">Common Methods</span>
1. initialize `XHR Object`
2. `open` method to specify requesting URL
- `httpRequest.open(method, url, async);`
3. `send` to send request
- first param of this method can be used to transform message (like using POST)
```javascript=
httpRequest.open('POST', '/api/test.php');
httpRequest.send('name=value&anothername=' + encodeURIComponent(myVar) + '&so=on');
```
### <span class="intext-point">set Header</span>
```javascript=
// when using 'POST'
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
```
### <span class="intext-point">get Header</span>
```javascript=
XMLHttpRequest.getResponseHeader(name);
// example
var httpRequest = new XMLHttpRequest();
httpRequest.getResponseHeader('Content-Type');
```
## <span class="intext-title">Properties</span>
| Property | Description | Data Format |
| ------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| readyState |current XHR Object status| `0` (uninitialized), `1` (loading), `2` (loaded), `3` (interactive), `4` (complete) |
| status |Returned HTTP status|`200`: ok, `403`: forbidden, `404`: page not found|
| responseText |Data returned from server|String|
| onreadystatuschange | use to bind `callback` function which will be called once the object status has changed | |
### <span class="intext-point">XMLHttpRequest.onreadystatechange</span>
```javascript=
var httpRequest = new XMLHttpRequest();
// Bind callback function
httpRequest.onreadystatechange = function(){
// Judge if XHR Object is ready
if (httpRequest.readystate === 4){
// Jedge status code
if (httpRequest.status == 200){
// Deal with responded data
alert(httpRequest.responseText);
var response = JSON.parse(httpRequest.responseText);
}
}
}
```
## <span class="intext-title">Combinational Example</span>
```javascript=
var httpRequest;
if (window.XMLHttpRequest){
httpRequest = new XMLHttpRequest();
}
else {
httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
// set up callback function
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState === 4){
if (httpRequest.Status == 200){
var jsonResponse = JSON.parse(httpRequest.responseText);
var userData = document.getElementById("user");
userData.innerHTML = jsonResponse.userName;
}
else{
alert(`STATUS CODE ERROR -- ${httpRequest.status}`)
}
}
}
httpRequest.open('GET', 'api/get_user_data');
httpRequest.send(null);
```
# Web APIs
## Event
### Event target
`Event.target` and `Event.currentTarget`