Showing posts with label HTML5 自修課. Show all posts
Showing posts with label HTML5 自修課. Show all posts

Friday, July 6, 2012

第二堂 JavaScript:: 2dolist

之前提到的:
HTML5 = HTML markup (架構) + CSS style (外觀) + JaveScript APIs (行為)
或許每個人對於這些名詞的定義與從屬關係有不同的看法,不過可以確定的是
JavaScript is the default language of HTML5.
關於 JavaScript 以下有兩本我覺得很有幫助的參考書:
 - JavaScript: The Good Parts (蝴蝶書)
 - Maintainable JavaScript (烏龜書)
當然,使用 HTML 和 CSS 就可以寫出非常好看的靜態網頁,有興趣可參考 Zen Garden 裡的 | 文說明範例;然而,如果想要跟上 web development 的時尚腳步,做出 Chrome Experiments 裡的互動網頁,讓朋友在 fb 上分享,JavaScript 是其中不可缺少利器之一。So, let's take some time and have a little fun with a simple example :]


如何讓 HTML 裡的 element 由 JavaScript 來控制做出互動效果呢? JavaScript 和 HTML 之間的溝通需要靠另一位小幫手 Document Object Model (DOM)。DOM 怎麼來的?
當瀏覽器 parse HTML 檔案的同時,它會產生一個像樹狀的圖 (也就是 internal model),這個圖解構 HTML 檔案裡所有 element 的關係。JavaScript 也就是靠著 DOM 對 HTML 的了解,取得這些 element 的資訊再加入互動行為。當 JavaScript 完成修改後,我們的瀏覽器會動態更新而成就互動網頁,可參考此關係圖。以範例中的 text input, button 和 displaylist 來看它們如何對話:
STEP1. Set up an event handler: when the button (id="btn1") is clicked..
STEP2. Write the handler to get the value from the text input (id="wt2do").
STEP3. Create a new "li" element to hold this value.
STEP4. Add the element to the page's DOM ("ul" id="displaylist").

2dolist.html
<!doctype html>
<html>
  <head>
    ...
    <script src="2dolist.js"></script>
  </head>
  <body>
    <h1>2 Do:</h1>
    <div>
      <input type="text" id="wt2do" size="30" placeholder="What's in your mind?">
      <input type="button" id="btn1" value="add">
      <input type="button" id="btn2" value="remove list">     
      ...
    </div>
    <ul id="displaylist"></ul> 
    ...
  </body>
</html>

2dolist.js
var todolist = null;

function init(){
  /* add event handler for button add*/
  document.getElementById("btn1").addEventListener('click', onClickedBtnAdd);  //STEP 1
  ...
  /* load todo list from the storage; or if none, create a new one*/
  todoList = loadDisplaylist();
  if (todoList === null){  
    todoList = document.getElementById("displaylist");
  }    
}

function onClickedBtnAdd(){

  /* get the input text */
  var input = document.getElementById("wt2do").value,  //STEP 2
      todoItem = null;
       
  /* if the input value is available, add to the list */
  if (input !== ""){
    todoItem = addTodoItem(input, todoList);
    save(todoItem);
  }
  ...
}

function addTodoItem(item, ul){   
  li = document.createElement("li");  //STEP 3.1
  li.textContent = item;              //STEP 3.2
  ul.appendChild(li);                 //STEP 4
  ...
  return li;
}

想了解更多關於 Event Handler,這裡有兩篇不錯的文章:
 - Traditional model: Ex. element.onclick = doSomething;
 - Advanced models: Ex. element.addEventListener('click',doSomething,false);
或許有人會覺得,怎麼好像沒看到 HTML5 的半點影子呢?嘿嘿,最後就讓我們利用一下 HTML5 的 localStorage 把 displaylist 存起來吧!
2dolist_storage.html
var STORAGE_LIST_KEY = "displaylist";

function save(item){
    var displaylistArray = getStoreArray(STORAGE_LIST_KEY);
    displaylistArray.push(item.textContent);
    localStorage.setItem(STORAGE_LIST_KEY, JSON.stringify(displaylistArray));
}

function clearDisplaylist(){
    localStorage.clear(STORAGE_LIST_KEY);
}

function loadDisplaylist(){
    ...
    return list;
}

function getStoreArray(key){
    var displaylistArray = localStorage.getItem(key);
    if(displaylistArray === null || displaylistArray === ""){      displaylistArray = [];
    } else{
        displaylistArray = JSON.parse(displaylistArray);
    }
    return displaylistArray;
}
...

Monday, July 2, 2012

第一堂 HTML5 Intro:: Hello World

開學囉,今天開始新的自主練習寫 HTML5。從小被老師寵慣的我,總是有考試和 deadlines 逼著我念書,要自己主動學習,似乎變得不太自然。經過幾番掙扎後,還是不免俗的來一個 Hello World:


headfirsthtml5.html: from HTML to HTML5 (code with black color)
<!doctype html>
<html>
  <head>
    <title>Hello World</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="first.css">
    <script src="first.js"></script>
  </head>
  <body>
    <div id="counterInJS"></div>
    <h1>Hi, HTML5</h1>
    <p>
      <img src="html5_back_cover.gif" alt="reference page">
    </p>
    <p>
      <div>Reference books:
      <ul>
        <li><a href=".. ">Head first HTML5 Programmin</a></li>
        <li><a href=".. ">JavaScript: The Good Parts</a></li>
      </ul></div>
      <div class="note">
        Yoopii! This is the starting my HTML5 and Javascript!<br>
        - by Pomm (-:</div>
    </p>
  </body>
</html>


first.js: a counter example
var c = "";
var count = 300;
var counting = setInterval(function(){counter()},1000);

function counter(){
   
    if (count > 0){
        c = "Javascript is loading in.. " + count;
        count = count - 1;
    } else {
        c = "Congrats! Loading completed!!";
        clearInterval(counting);
    }
    document.getElementById("counterInJS").textContent = c;
    //why textContent rather than innerHTML?
    //http://dochub.io/#dom/element.innerhtml
}

window.onload = counting;
//vs. using element.addEventListener()!?
//http://dochub.io/#dom/window.onload

first.css: formating
/*HTML Elements*/
body,
h1, h2, h3,
p {
    font-family: Arial, Helvetica, sans-serif;
    line-height: 120%;
}
h1 {
    color:orange;
    text-shadow: 0 0 0.2em #CCC;
}
a:link, a:visited {color:grey;}
a:hover {color:cornflowerblue;}

/*Page Elemets*/
#counterInJS {
    font-family: courier;
}

/*Other classes*/
.note{
    font-size: small;
}

HTML5 is made up of a family of technology. In the book of Head first HTML5, it give an unofficial definition: HTML5 = HTML markup + JavaScript APIs + CSS. (also see another intro in Chinese.) One of the design principles behind HTML5 is to allowed your pages to degrade gracefully.

Software Requirements:
To write HTML5 and Javascript, you are good to go with a text editor, a brower, and sometimes a webserver. There are many editors available for Windows users such as PSPad, TextPad, EditPlus, Notepad++, or Notepad (if this is all you have). It's also encouraged to use more than one browsers for testing. Chrome and Safari, in general, are the most up-to-date. Other major browsers including Firefox, Opera, and IE are also worth to try. I'm currenlty practicing on Notepad++ with Firefox(firebug) and Chrome(developer tools and Javascript console).

Reference:
http://dochub.io/ (Mozilla Documentation)
W3School vs W3Fool (debate articles: 1 2.. )
caniuse.com (So, who is ready for up to date HTML5 and CSS?)