JavaScript DOM EventListener

JavaScript DOM EventListener

Syntax

element.addEventListener(event, function, useCapture);

The first parameter is the type of the event(like "click" NOT "onclick")

document.getElementById("alertShow").addEventListener("click", function(){alert("Hello!")});

//↕ same function 

document.getElementById("alertShow").addEventListener("click", fAlert);

function fAlert() {
  alert("Hello!");
}
color picker

↕ &x2195;(Hex) ↕ ↕(Dec)

HTML unicode UTF-8

Bubbling:

useCapure: false(default)

↑ paragraph First, then division

Capturing:

useCapure: true

↑ division First, then paragraph


useCapture: true だと 外側から優先 <div> → <p>
defalt: false だと 内側から優先 <p> → <div>

propagation 繁殖 伝播 遺伝 普及 伝達

    //useCapture false(default) true
    document.getElementById("eventB").addEventListener("click", function() {
      alert("Bubbling divisoin")
    }, false);

    document.getElementById("pB").addEventListener("click", function(){
      alert("Bubbling paragraph")
    }, false);

    document.getElementById("eventC").addEventListener("click", function(){
      alert("Capturing divisoin")
    }, true);

    document.getElementById("pC").addEventListener("click", function(){
      alert("Capturing paragraph")
    }, true);




 //Counter self-invoking function
  var add = (function(){
    var counter = 0;
    return function () {counter += 1; return counter;}
  })();
var MC1 = document.getElementById("CM1");
MC1.addEventListener("click", MOverCount);
MC1.addEventListener("mouseover", MOver1);
  function MOverCount(){
    document.getElementById("CountM1").innerHTML = add();
  }
function MOver1() {
  document.getElementById("CountM1").innerHTML =
  "mouseovered!"
}
  var add1 = (function(){
    var counter = 0;
    return function () {counter += 1; return counter;}
  })();
 var MO1 = document.getElementById("CM2");
 MO1.addEventListener("mouseover", MOverCount1);
 MO1.addEventListener("click", ClickM1);
  function MOverCount1() {
    document.getElementById("CountM2").innerHTML = add1() +"<br>";
  }
  function ClickM1(){
    document.getElementById("CountM2").innerHTML += "Clicked!" +"<br>";
  }
  

onmouseover だとstep 2 の値が出る
add.EventListener("mouseover", MOverCount1); とすれば正確な値が出る

JavaScript Function Closures, onmouseover event

child nodes and node value

<title id=practice">DOM Tutorial</title>

The element node <title> DOES NOT contain text.
It contains a text node with the value"DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property.

var myTitle = documentgetElementById("practice").innerHTML;

//↕

var myTitle = document.getElementById("practice").firstChild.nodeValue;

//↕

var myTitle = document.getElementById("practice").firstChild[0].nodeValue;

<p style="border: 1px solid black"> などでも<p>はstyle attribute を持つ。
<img src="" width="" height=""> や <p title="tooltip"> などもattribute

 // ↑
  //nodeName
  document.getElementById("nodePractice1").innerHTML = document.getElementById("alertShow").nodeName;

  nodeName always contains the uppercase tag name.

nodeValue for element nodes is null

nodeType property

node Type example
ELEMENT_NODE 1 <h1 class="Header">practice</h1>
ATTRIBUTE_NODE 2 class="Header"
TEXT_NODE 3 practice
COMMENT_NODE 8 <!---something comment-->
DOCUMENT_NODE 9 The HTML document itself (the parent of <html>)
DOCUMENT_TYPE_NODE 10 <Doctype html>
<style>
table, th, td {
  /*border:1px solid black;*/
  border-collapse:collapse;
  text-align: left;
  padding: 8px;
 }
tr {border-bottom: 1px solid #ddd;}
tr:nth-child(even) {background-color:#f2f2f2; 
</style>
~~~~~~~
<table style="border: 1px solid black;">
    <colgroup>
    <col span="2" style="background-color: lightblue;"></col>
    <col span="1" style="background-color: khaki;"></col>
  </colgroup>
  <tr>
    <td>node</td>
    <td>Type</td>
    <td>example</td>
  </tr>

appendChild()

this is a paragraph.

This is another paragraph.







  //appendChild()
  function nodePractice2() {
    var para = document.createElement("p");
    var node = document.createTextNode("This is NEW. added by appendChild()");
    para.appendChild(node);
    var element = document.getElementById("nodeP1");
    element.appendChild(para);
  }
  //insertBefore()
  function nodePractice3() {
    var para = document.createElement("p");
    var node = document.createTextNode("insertBefore method!");
    para.appendChild(node);
    
    var element = document.getElementById("nodeP1");
    var child = document.getElementById("Np2");
    element.insertBefore(para, child);
  }
  //remove
  function nodePractice4(){
    var parent = document.getElementById("nodeP1");
    var child = document.getElementById("nodeP1").lastChild;
    parent.removeChild(child);
    //child.parentNode.removeChild(child); 
    //common workaround finding the child
  }
  //replaceChild()
  function nodePractice5(){
  var child =document.getElementById("Np1");
  var para = document.createElement("p");
  var node = document.createTextNode("This is replaced.");
  para.appendChild(node);
  child.parentNode.replaceChild(para, child);
}
    

//BOM
var w = window.outerWidth;
var h = window.outerHeight;
text1 = document.getElementById("windowsize").innerHTML = 
"Your Browser width is: " + w + " and height is: " + h;
function showResize() {
var w = window.outerWidth;
var h = window.outerHeight;
text1 = document.getElementById("windowsize").innerHTML = 
"Your Browser width is: " + w + " and height is: " + h;
}

window.Width; window.Height; Width Height と最初が大文字

style="margin: 10px 50px 10px 50px;

//,は要らない

screen.width; screen.height; width height は小文字

avail.Widht; avail.Height; Width Height と最初が大文字

table のresponsib化がうまくいかない(?in firefox 縦タブ)
@media screen and (max-width: 768px)
table, tr, td {width: 80%; overflow-x: auto; padding:0 20px 0 20px;}

chromnium browser でも拡大したときのtable overflow-x: auto/scroll がうまくいかない。
width:768px 以下のresponsib化時の<span class="green">で指定した vwでの表示により文字の大きさが普段と拡大で少しだけ逆転する。

枠に入り切らない長い文章がある列の <th> や <td> にstyle="width: 250px;" のように幅を指定することで@media screen and (max-width: 768px){} のときに拡大しても全体のwidth内に収まるようにはなった。

window location
window.location.href
window.location.hostname
window.location.pathname
window.location.protocol
window.location.assign()


Confirm box: confirm()

script内での改行 \n newline, \r carrige return, \v vertical tabulator,
\b backspace, \f form feed, \t hotizontal tabulator

//confirm box
function confirmP() {
  var txt ;
  if (confirm("Press a button.\nボタンを押してください")) {
    txt = "You pressed OK!" + "
" + "OK ボタンが押されました。"; } else { txt = "You pressed Cancel." + "
" + "キャンセルされました。"; } document.getElementById("confirmPractice").innerHTML = txt; }

Prompt box
window.prompt("sometext", "default text");

//prompt box
function promptP(){
  var txt;
  var person = prompt("Please enter your name.\n名前を入力してください。", "Ted Mosby");
  if (person == null || person == "") {
    txt = "User cancelled the prompt" + "<br>" + "プロンプトはキャンセルされました。";
  } else {
    txt = "Hello " + person + "! How are you today?" + 
    "<br>" + "こんにちは " + person + "さん、 ご機嫌いかがですか。";
  }
  document.getElementById("promptPractice").innerHTML = txt;
}

"||" logical OR
"?:" condition
"&&" logical AND
"!" logical not ""
Arithmetic

setTimeout(function, milliseconds)
clearTimeout(timeoutVariable)

setInerval(function, milliseconds)
clearInterval(timerVariable)

clock

onpageshow="" は<body>しかサポートしてない。
onload Event, onpageshow Event

oload Event を<div> , <p> にaddEventListener("load", functionname) で加えてもサポートされていないから load してもfunction() が機能しない。 *1

onload Event suppoted HTML tag: <body>, <frame>, <iframe>, <img<, <input type="image">, <link>, <script>, <style>

onpageshow Event をwindow.addEventListener("pageshow", startTime); BOM(Browser Object Model)を使う。
"pageshow" event is attached to the window object using the addEventListner() method.

<div>
  <p id="LT1">clock</p>
  <p id="setTimeoutPractice"></p>
</div>
<script>
//setTimeout() <body onload="startTime()">
{
//document.getElementById("LT1").addEventListener("load", startTime); *1 
↓
window.addEventListener("pageshow", startTime);
function startTime() {
  let time = new Date();
  let h = time.getHours();
  let m = time.getMinutes();
  let s = time.getSeconds();
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById("setTimeoutPractice").innerHTML = h + ":" + m + ":" + s;
  let t = setTimeout(startTime, 500);  //1000で1秒 1秒以内にループさせたい

}
function checkTime(i) {
  if (i < 10) {i = "0" + i};
  return i;
}
}

↑grid内のレイアウトはautoに任せて、gridのcontainer全体に対してoverflowを指定した方がキレイかな?

var d = new Date();
document.getElementById("day").innerHTML = d.getDay();

//returns 0 to 6 indexed number

//use array to show what day
var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("day1").innerHTML = days[d.getDay()];
date get methods

JavaScript cookie 難しい


.substring(), .split()

string.substring(strat, end) : string.split(separator, limit)

AJAXを何となく分かるまでの準備メモ

HTML5 server-sent event
If there are any update contets available, with a server-sent events the updates come automatically.
Exapmles:Twitter updates, stock price, any news etc.

HTML5 Server-Sent Events
var source = new EventSource("some.php");
source.onmessage = function(event) {
  document.getElementById("someResult").innerHTML += event + "
" };

server-side

  
>?php
header('Content-Type: text/event-strem');
header('Chache-Control: no-cache');

$time = date('r')
echo "data: The server time is: {$time}\n\n";
  flush();
?>

"Content-Type" "MIME" typesMDN MIME types
application/octetstream, text/plain, text/css, text/html, text/javascript, image/gif, image/jpeg, audio/webm, video/webm, multipart/form-data, multipart/byteranges ...

MIME(Multipurpose Internet Mail Extentions)

XMLHttpRequest() is object.

access across domains: MDN にはrequestに外部へのXMLにaccessしてもいいかの許可を出してOKならばweb pageに載せることが出来ると理屈としては許可をだしてもいいようだが、 security reasons によりmodern browsers はこれを禁止している。XML ファイル自体を同じサーバーに持ってくればOKだが、複製許可が有るのかも聞かないといけない。

Asynchronous true: can excute other scripts while waiting sever response.

table に"YEAR"足してみた

TagName getElementsByTagName("")
"CD"が0からたくさんあって、"CD"内にある各種Tagは一つしか無いから[0]で簡単に指定出来る。
innerHTMLはXMLに使えないからnodeValue で内容を入手してくる。DOM collection page上のnodeメモに移動

XMLHttpRequest Object

AJAX PHP HTML Form attributes

Suggestions:

First name:

AJAX PHP写経してgethint.phpファイルを同じディレクトリに置いてみたが、もちろん動かない

AJAX database

Customer info will be listed here...

  function showCustomer(){
/* var x = document.getElementById("formP").value; */
var x = document.getElementById("formP").selectedIndex;
/*var y = document.getElementsByTagName("option")[x].label;*/
/*var ALFKI; = "<table><tr><th>CustomerID</th><td>ALFKI</td></tr><tr><th>CompanyName</th><td>Alfreds Futterrkiste</td></tr><tr><th>ContactName</th><td>Maria Andres</td></tr></table>";
var NORTS = "<table><tr><th>CustomerID</th><td>NORTS</td></tr><tr><th>CompanyName</th><td>North/South</td></tr><tr><th>CompanyName</th><td>Simon </td></tr></table>";
var WOLZA = "<table><tr><th>CustomerID</th><td>WOLZA</td></tr><tr><th>CompanyName</th><td>Wolski Zbyszek</td></tr><tr><th>CompanyName</th><td>Zbyszeki </td></tr></table>"; */
text1 = 
"<table><tr><th>CustomerID</th><td>ALFKI</td></tr><tr><th>CompanyName</th><td>Alfreds Futterrkiste</td></tr><tr><th>ContactName</th><td>Maria Andres</td></tr></table>";
text2 = 
"<table><tr><th>CustomerID</th><td>NORTS</td></tr><tr><th>CompanyName</th><td>North/South</td></tr><tr><th>CompanyName</th><td>Simon </td></tr></table>";
text3 = 
"<table><tr><th>CustomerID</th><td>WOLZA</td></tr><tr><th>CompanyName</th><td>Wolski Zbyszek</td></tr><tr><th>CompanyName</th><td>Zbyszeki </td></tr></table>";
try {
if (x == 1){
document.getElementById("txtHint1").innerHTML = text1;
} else if (x == 2) {
document.getElementById("txtHint1").innerHTML = text2;
} else if (x == 3){
document.getElementById("txtHint1").innerHTML = text3;
} else {
document.getElementById("txtHint1").innerHTML = "JavaScript test";
} 
}catch(err) {
  document.getElementById("txtHint1").innerHTML = err;
}
}

  

form select value をif, else if, if での条件指定 がうまくいかない switch だと一度選んだら止まる(?)

valueのように<select id="formP" onchange="showCustomer()">getElementById("formP").value; で直接<option valuse=""> のstringを持ってきてもらおうとするが… referenceError, var で直接declare も最初で止まる
selecteIndexにしたら失敗してたのが何処行った?みたいにうまく行った。

label try it に行った変更のようにしてみたかった。


function DomOptionP() {
  var i =document.getElementById("selectPractice").selectedIndex;
  /*
  var ALFKI = document.getElementsByTagName("option")[1];
  var NORTS = documentgetElementsByTagName("option")[2];
  var WOLZA = documentgetElementsByTagName("option")[3];*/
 
  switch (i) {
  case 1:
    document.getElementById("optionPractice").innerHTML = 
    "<table><tr><th>CustomerID</th><td>ALFKI</td></tr><tr><th>CompanyName</th><td>Alfreds Futterrkiste</td></tr><tr><th>ContactName</th><td>Maria Andres</td></tr></table>";
  break;
  case 2:
    document.getElementById("optionPractice").innerHTML = 
    "<table><tr><th>CustomerID</th><td>NORTS</td></tr><tr><th>CompanyName</th><td>North/South</td></tr><tr><th>CompanyName</th><td>Simon </td></tr></table>";
    break;
  case 3:
    document.getElementById("optionPractice").innerHTML = 
    "<table><tr><th>CustomerID</th><td>WOLZA</td></tr><tr><th>CompanyName</th><td>Wolski Zbyszek</td></tr><tr><th>CompanyName</th><td>Zbyszeki </td></tr></table>";
    break;
  default:
    document.getElementById("optionPractice").innerHTML ="JavaScript Practice";
  } 
}
↑switch(expression) {
case 1:
  //code
break;
case 2:
//code
break;
case 3:
//code
break;
default:
//code
}

switchの expression を表現するのに苦労
<select> id="selectPractice" .selectedIndex からindex number を持ってきてもらう。
あとは、無理やりtableを書いてみてXMLHttpRequset したときの動きを再現。nodemap からのアクセスも書いてみないと…

select objectselectedindex, switch

HTML DOM Option object

ReferenceErrorが出て、switch に変更。途中case: の後にbreak:を付け忘れcase 1 or 2 or 3のどれか2つだけ表示される。option から直接valueを持ってきて欲しかったがstring < number を実感。

Option Object

    //.options.value
function ValueP1() {
  var x = document.getElementById("valuePractice").selectedIndex;
  var y = document.getElementById("valuePractice").options;
var i;
/*var i = document.getElementById("valuePractice").selectedIndex.options.value; */ 
// 変なvariables があるとfunction が止まってしまう。

  if (y[x].value == "apple"){
    document.getElementById("DomValue").innerHTML = "Apple";
    } else if (y[x].value == "banana") {
      document.getElementById("DomValue").innerHTML = "Banana";
    } else if (y[x].value == "orange") {
      document.getElementById("DomValue").innerHTML = "Orange";
    } else {
      document.getElementById("DomValue").innerHTML ="Pineapple";
    }
  }

  

<option value=""> を指定
document.getElementById("id").selectedIndex.options.value;


<select id="valuePractice1" onchange="ValueP2()">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="pineapple">Pineapple</option>
  <option value="orange">Orange</option>
</select>

<script>
  //options
function ValueP2(){
function ValueP2(){
  var x = document.getElementById("valuePractice1").selectedIndex;
  var y = document.getElementById("valuePractice1").options;
var i = y[x].value; 


 if (i == "apple") {
 document.getElementById("DomValue2").innerHTML = 
 "y[0].text means " + y[x].text + ".selectedIndex.options.value; is " + i;
} else if (i == "banana") {
  document.getElementById("DomValue2").innerHTML = 
  "y[1].text is " + y[x].text + ".selectedIndex.options.value; is " + i;
} else if (i == "orange"){
  document.getElementById("DomValue2").innerHTML = 
  "y[3].text is " + y[x].text + ".selectedIndex.options.value; is " + i;
} else {
  document.getElementById("DomValue2").innerHTML = 
  "y[2].text is " + y[x].text + ".selectedIndex.options.value; is " + i;
} /*catch(err) { 
  document.getElementById("DomValue2").innerHTML = err;
} */

document.getElementById("DomValue1").innerHTML =
"Index: " + y[x].index + " is " + y[x].text + "<select > .options[" + 
y[x].index + "].value(y[x].value) is " +  y[x].value;

}
  

.label // optionObject.label
If label attribute is empty returns <option> element text(content).

input attributes
<input list="browses">
<datalist id="browsers">
<option value="IE">...

input list="name" と datalist id="name" は同じじゃないと機能しない。

↓datalist

index 2

id と function name が同じではダメ、datalist にはselectedIndex が効かない(?)
<datalist onchange="datalistP()"> onchange でfunctionを呼び出したかった。

onchange Eventによると単に<datalist> はsupport されていなかった。
<select> <textarea> 多くの<input type=""> がsupportされている。

↓select


CustomerID WOLZA
CompanyName Wolski Zajazas
ContactName Zbyszek PiestZeniev
Adress ul.Filtrowa 68
City Warszawa
PostalCode o1-012
Country Poland

tryに無理やりbookを足してreturn するかの実験

& & ; &apos ;

XML /URI Uniform Resource Identifier /URN Uniform Resource Name