2019年10月15日 星期二

JavaScript HTML DOM Events

Reacting to Events

< !DOCTYPE html>
< html>
< body>

< h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!< /h1>

< /body>
< /html>



HTML Event Attributes

< !DOCTYPE html>
< html>
< body>

< button onclick="displayDate()">Try it< /button>

< /body>
< /html>



Assign Events Using the HTML DOM

< script>
document.getElementById("myBtn").onclick = displayDate;
< /script>



The onload and onunload Events

< body onload="checkCookies()">



The onchange Event

< input type="text" id="fname" onchange="upperCase()">




The onmouseover and onmouseout Events

< !DOCTYPE html>
< html>
< body>

< div onmouseover="mOver(this)" onmouseout="mOut(this)" 
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me< /div>

< script>
function mOver(obj) {
  obj.innerHTML = "Thank You"
}

function mOut(obj) {
  obj.innerHTML = "Mouse Over Me"
}
< /script>

< /body>
< /html> 




The click Events

< !DOCTYPE html>
< html>
< body>

< div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me< /div>

< script>
function mDown(obj) {
  obj.style.backgroundColor = "#1ec5e5";
  obj.innerHTML = "Release Me";
}

function mUp(obj) {
  obj.style.backgroundColor="#D94A38";
  obj.innerHTML="Thank You";
}
< /script>

< /body>
< /html> 



onfocus

< !DOCTYPE html>
< html>
< head>
< script>
function myFunction(x) {
  x.style.background = "yellow";
}
< /script>
< /head>
< body>

Enter your name: < input onfocus="myFunction(this)" type="text" />

< p>When the input field gets focus, a function is triggered which 
changes the background-color.< /p>

< /body>
< /html>



HTML DOM Events


Event Description Belongs To
abort The event occurs when the loading of a media is aborted UiEventEvent
afterprint The event occurs when a page has started printing, or if the print dialogue box has been closed Event
animationend The event occurs when a CSS animation has completed AnimationEvent
animationiteration The event occurs when a CSS animation is repeated AnimationEvent
animationstart The event occurs when a CSS animation has started AnimationEvent
beforeprint The event occurs when a page is about to be printed Event
beforeunload The event occurs before the document is about to be unloaded UiEventEvent
blur The event occurs when an element loses focus FocusEvent
canplay The event occurs when the browser can start playing the media (when it has buffered enough to begin) Event
canplaythrough The event occurs when the browser can play through the media without stopping for buffering Event
change The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>) Event
click The event occurs when the user clicks on an element MouseEvent
contextmenu The event occurs when the user right-clicks on an element to open a context menu MouseEvent
copy The event occurs when the user copies the content of an element ClipboardEvent
cut The event occurs when the user cuts the content of an element ClipboardEvent
dblclick The event occurs when the user double-clicks on an element MouseEvent
drag The event occurs when an element is being dragged DragEvent
dragend The event occurs when the user has finished dragging an element DragEvent
dragenter The event occurs when the dragged element enters the drop target DragEvent
dragleave The event occurs when the dragged element leaves the drop target DragEvent
dragover The event occurs when the dragged element is over the drop target DragEvent
dragstart The event occurs when the user starts to drag an element DragEvent
drop The event occurs when the dragged element is dropped on the drop target DragEvent
durationchange The event occurs when the duration of the media is changed Event
ended The event occurs when the media has reach the end (useful for messages like "thanks for listening") Event
error The event occurs when an error occurs while loading an external file ProgressEventUiEventEvent
focus The event occurs when an element gets focus FocusEvent
focusin The event occurs when an element is about to get focus FocusEvent
focusout The event occurs when an element is about to lose focus FocusEvent
fullscreenchange The event occurs when an element is displayed in fullscreen mode Event
fullscreenerror The event occurs when an element can not be displayed in fullscreen mode Event
hashchange The event occurs when there has been changes to the anchor part of a URL HashChangeEvent
input The event occurs when an element gets user input InputEventEvent
invalid The event occurs when an element is invalid Event
keydown The event occurs when the user is pressing a key KeyboardEvent
keypress The event occurs when the user presses a key KeyboardEvent
keyup The event occurs when the user releases a key KeyboardEvent
load The event occurs when an object has loaded UiEventEvent
loadeddata The event occurs when media data is loaded Event
loadedmetadata The event occurs when meta data (like dimensions and duration) are loaded Event
loadstart The event occurs when the browser starts looking for the specified media ProgressEvent
message The event occurs when a message is received through the event source Event
mousedown The event occurs when the user presses a mouse button over an element MouseEvent
mouseenter The event occurs when the pointer is moved onto an element MouseEvent
mouseleave The event occurs when the pointer is moved out of an element MouseEvent
mousemove The event occurs when the pointer is moving while it is over an element MouseEvent
mouseover The event occurs when the pointer is moved onto an element, or onto one of its children MouseEvent
mouseout The event occurs when a user moves the mouse pointer out of an element, or out of one of its children MouseEvent
mouseup The event occurs when a user releases a mouse button over an element MouseEvent
mousewheel Deprecated. Use the wheel event instead WheelEvent
offline The event occurs when the browser starts to work offline Event
online The event occurs when the browser starts to work online Event
open The event occurs when a connection with the event source is opened Event
pagehide The event occurs when the user navigates away from a webpage PageTransitionEvent
pageshow The event occurs when the user navigates to a webpage PageTransitionEvent
paste The event occurs when the user pastes some content in an element ClipboardEvent
pause The event occurs when the media is paused either by the user or programmatically Event
play The event occurs when the media has been started or is no longer paused Event
playing The event occurs when the media is playing after having been paused or stopped for buffering Event
popstate The event occurs when the window's history changes PopStateEvent
progress The event occurs when the browser is in the process of getting the media data (downloading the media) Event
ratechange The event occurs when the playing speed of the media is changed Event
resize The event occurs when the document view is resized UiEventEvent
reset The event occurs when a form is reset Event
scroll The event occurs when an element's scrollbar is being scrolled UiEventEvent
search The event occurs when the user writes something in a search field (for <input="search">) Event
seeked The event occurs when the user is finished moving/skipping to a new position in the media Event
seeking The event occurs when the user starts moving/skipping to a new position in the media Event
select The event occurs after the user selects some text (for <input> and <textarea>) UiEventEvent
show The event occurs when a <menu> element is shown as a context menu Event
stalled The event occurs when the browser is trying to get media data, but data is not available Event
storage The event occurs when a Web Storage area is updated StorageEvent
submit The event occurs when a form is submitted Event
suspend The event occurs when the browser is intentionally not getting media data Event
timeupdate The event occurs when the playing position has changed (like when the user fast forwards to a different point in the media) Event
toggle The event occurs when the user opens or closes the <details> element Event
touchcancel The event occurs when the touch is interrupted TouchEvent
touchend The event occurs when a finger is removed from a touch screen TouchEvent
touchmove The event occurs when a finger is dragged across the screen TouchEvent
touchstart The event occurs when a finger is placed on a touch screen TouchEvent
transitionend The event occurs when a CSS transition has completed TransitionEvent
unload The event occurs once a page has unloaded (for <body>) UiEventEvent
volumechange The event occurs when the volume of the media has changed (includes setting the volume to "mute") Event
waiting The event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data) Event
wheel The event occurs when the mouse wheel rolls up or down over an element WheelEvent



HTML DOM Event Properties and Methods

Property/Method Description Belongs To
altKey Returns whether the "ALT" key was pressed when the mouse event was triggered MouseEvent
altKey Returns whether the "ALT" key was pressed when the key event was triggered KeyboardEventTouchEvent
animationName Returns the name of the animation AnimationEvent
bubbles Returns whether or not a specific event is a bubbling event Event
button Returns which mouse button was pressed when the mouse event was triggered MouseEvent
buttons Returns which mouse buttons were pressed when the mouse event was triggered MouseEvent
cancelable Returns whether or not an event can have its default action prevented Event
charCode Returns the Unicode character code of the key that triggered the onkeypress event KeyboardEvent
changeTouches Returns a list of all the touch objects whose state changed between the previous touch and this touch TouchEvent
clientX Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered MouseEventTouchEvent
clientY Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered MouseEventTouchEvent
clipboardData Returns an object containing the data affected by the clipboard operation ClipboardData
code Returns the code of the key that triggered the event KeyboardEvent
composed Returns whether the event is composed or not Event
createEvent() Creates a new event Event
ctrlKey Returns whether the "CTRL" key was pressed when the mouse event was triggered MouseEvent
ctrlKey Returns whether the "CTRL" key was pressed when the key event was triggered KeyboardEventTouchEvent
currentTarget Returns the element whose event listeners triggered the event Event
data Returns the inserted characters InputEvent
dataTransfer Returns an object containing the data being dragged/dropped, or inserted/deleted DragEventInputEvent
defaultPrevented Returns whether or not the preventDefault() method was called for the event Event
deltaX Returns the horizontal scroll amount of a mouse wheel (x-axis) WheelEvent
deltaY Returns the vertical scroll amount of a mouse wheel (y-axis) WheelEvent
deltaZ Returns the scroll amount of a mouse wheel for the z-axis WheelEvent
deltaMode Returns a number that represents the unit of measurements for delta values (pixels, lines or pages) WheelEvent
detail Returns a number that indicates how many times the mouse was clicked UiEvent
elapsedTime Returns the number of seconds an animation has been running AnimationEvent
elapsedTime Returns the number of seconds a transition has been running
eventPhase Returns which phase of the event flow is currently being evaluated Event
getTargetRanges() Returns an array containing target ranges that will be affected by the insertion/deletion InputEvent
getModifierState() Returns an array containing target ranges that will be affected by the insertion/deletion MouseEvent
inputType Returns the type of the change (i.e "inserting" or "deleting") InputEvent
isComposing Returns whether the state of the event is composing or not InputEventKeyboardEvent
isTrusted Returns whether or not an event is trusted Event
key Returns the key value of the key represented by the event KeyboardEvent
key Returns the key of the changed storage item StorageEvent
keyCode Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event KeyboardEvent
location Returns the location of a key on the keyboard or device KeyboardEvent
lengthComputable Returns whether the length of the progress can be computable or not ProgressEvent
loaded Returns how much work has been loaded ProgressEvent
metaKey Returns whether the "META" key was pressed when an event was triggered MouseEvent
metaKey Returns whether the "meta" key was pressed when the key event was triggered KeyboardEventTouchEvent
MovementX Returns the horizontal coordinate of the mouse pointer relative to the position of the last mousemove event MouseEvent
MovementY Returns the vertical coordinate of the mouse pointer relative to the position of the last mousemove event MouseEvent
newValue Returns the new value of the changed storage item StorageEvent
newURL Returns the URL of the document, after the hash has been changed HasChangeEvent
offsetX Returns the horizontal coordinate of the mouse pointer relative to the position of the edge of the target element MouseEvent
offsetY Returns the vertical coordinate of the mouse pointer relative to the position of the edge of the target element MouseEvent
oldValue Returns the old value of the changed storage item StorageEvent
oldURL Returns the URL of the document, before the hash was changed HasChangeEvent
onemptied The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects)
pageX Returns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggered MouseEvent
pageY Returns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggered MouseEvent
persisted Returns whether the webpage was cached by the browser PageTransitionEvent
preventDefault() Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur Event
propertyName Returns the name of the CSS property associated with the animation or transition AnimationEventTransitionEvent
pseudoElement Returns the name of the pseudo-element of the animation or transition AnimationEventTransitionEvent
region MouseEvent
relatedTarget Returns the element related to the element that triggered the mouse event MouseEvent
relatedTarget Returns the element related to the element that triggered the event FocusEvent
repeat Returns whether a key is being hold down repeatedly, or not KeyboardEvent
screenX Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered MouseEvent
screenY Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered MouseEvent
shiftKey Returns whether the "SHIFT" key was pressed when an event was triggered MouseEvent
shiftKey Returns whether the "SHIFT" key was pressed when the key event was triggered KeyboardEventTouchEvent
state Returns an object containing a copy of the history entries PopStateEvent
stopImmediatePropagation() Prevents other listeners of the same event from being called Event
stopPropagation() Prevents further propagation of an event during event flow Event
storageArea Returns an object representing the affected storage object StorageEvent
target Returns the element that triggered the event Event
targetTouches Returns a list of all the touch objects that are in contact with the surface and where the touchstart event occured on the same target element as the current target element TouchEvent
timeStamp Returns the time (in milliseconds relative to the epoch) at which the event was created Event
total Returns the total amount of work that will be loaded ProgressEvent
touches Returns a list of all the touch objects that are currently in contact with the surface TouchEvent
transitionend The event occurs when a CSS transition has completed TransitionEvent
type Returns the name of the event Event
url Returns the URL of the changed item's document StorageEvent
which Returns which mouse button was pressed when the mouse event was triggered MouseEvent
which Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event KeyboardEvent
view Returns a reference to the Window object where the event occurred UiEvent

JavaScript HTML DOM - Changing CSS

Changing HTML Style

< html>
< body>

< p id="p2">Hello World!< /p>

< script>
document.getElementById("p2").style.color = "blue";
< /script>

< p>The paragraph above was changed by a script.< /p>

< /body>
< /html>



Using Events

< !DOCTYPE html>
< html>
< body>

< h1 id="id1">My Heading 1< /h1>

< button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!< /button>

< /body>
< /html>

JavaScript HTML DOM - Changing HTML

Changing the HTML Output Stream


< !DOCTYPE html>
< html>
< body>

< script>
document.write(Date());
< /script>

< /body>
< /html>
< /code>




Changing HTML Content


< html>
< body>

< p id="p1">Hello World!< /p>

< script>
document.getElementById("p1").innerHTML = "New text!";
< /script>

< /body>
< /html>




Changing the Value of an Attribute


< !DOCTYPE html>
< html>
< body>

< h1 id="id01">Old Heading< /h1>

< script>
var element = document.getElementById("id01");
element.innerHTML = "New Heading";
< /script>

< /body>
< /html>

JavaScript HTML DOM Elements

Finding HTML Elements

To do so, you have to find the elements first. There are several ways to do this:
  • Finding HTML elements by id
  • Finding HTML elements by tag name
  • Finding HTML elements by class name
  • Finding HTML elements by CSS selectors
  • Finding HTML elements by HTML object collections



Finding HTML Element by Id

var myElement = document.getElementById("intro");



Finding HTML Elements by Tag Name

var x = document.getElementsByTagName("p");


var x = document.getElementById("main");
var y = x.getElementsByTagName("p");




Finding HTML Elements by Class Name

var x = document.getElementsByClassName("intro");





Finding HTML Elements by CSS Selectors

var x = document.querySelectorAll("p.intro");


The querySelectorAll() method does not work in Internet Explorer 8 and earlier versions.




Finding HTML Elements by HTML Object Collections

var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
  text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;




JavaScript HTML DOM Document

HTML Elements

Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name


Changing HTML Elements

Property Description
element.innerHTML =  new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element


Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream


HTML Objects

Property Description DOM
document.anchors Returns all <a> elements that have a name attribute 1
document.applets Returns all <applet> elements (Deprecated in HTML5) 1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Obsolete. Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document's encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1


DOM (Document Object Model) 概念

由於寫網頁常會需要操控 DOM 物件,且 DOM 物件為 Web UI 的基礎概念
因此用這篇文章來紀錄相關學習筆記
透過 DOM 的操作,可以重構整個 HTML 檔案,可任意添加、移除、改變其項目,上方那張橘色的圖即為 DOM 之完整架構圖,最上方是 Core ( DOM Level 1) ,再下來是 XML 、 HTML (DOM Level 2),甚至以下有許多的 Event (DOM Level 3),最下方是使用者端的 Event ,主要分為以下三種:
(1) KeyboardEvents :鍵盤事件
(2) TextEvent :文字事件
(3) MouseEvents:滑鼠事件
由於 DOM 是由節點組成的,故一個 DOM 的物件 ( ex. html 檔) 可能可以看成以下架構,即所有的 Node 組成了一個檔案數,HTML 裡面的每個元素、屬性、內容等都代表著其中一個節點,並不斷延伸:

圖片來源:http://www.w3school.com.cn/htmldom/dom\_nodes.asp
DOM 操作基本語法
操作語法最常用以下幾項:
(1) getElementById()
用法為
document.getElementById("ID");
例如
var choose = document.getElementById(‘choose’);
可以取出 HTML 內容當中 <div id=”choose”> test </div> 當中的 test 字串
ps. 此項目無法使用在 XML 檔案當中
(2) getElementsByTagName()
用法為
document.getElementsByTagName("標籤名稱");
例如
document.getElementsByTagName("p");
將會回傳文件當中的所有 <p> 元素內之內容
ps. 原本還有 getElementByNAme,但是在新版本的 DOM 中已被移除
使用 DOM 變數之內容
如果要把之前的內容取出,則可使用
var x=document.getElementsByTagName("p");
會將 <p> 裡面的內容,丟進 x 變數當中
如果有一個以上的 <p> 資料的話,則可以使用以下代碼 loop 取出資料
var x=document.getElementsByTagName("p");for (var i=0;i<x.length;i++){   // do something with each paragraph}
如果只取出特定項目,例如第4個項目,則可使用以下代碼
var y = x[3];
動態變更 HTML 的內容
現在在 html 當中有一行為
<div id=”content”> test </div>
如果要利用 JavaScript 更改內容的值,可使用以下代碼
var x = document.getElementById(“content”);
x.innerHTML = “newContent”;
如此一來,原本的 test 就會更改為新的內容,即 newContent
設定 Tag 屬性
我們有時候會需要針對 HTML 當中的 tag 新增一些屬性,可使用以下代碼
document.getElementById(‘choose’).style.fontWeight = ‘bold’;
上面那行的意思是說,針對 HTML 當中的 <div id=’choose’> test </div> 的 test ,新增粗體文字屬性
一個簡單的範例
var choose = document.getElementById(‘choose’);
0
以上範例的意思就是,在網頁上面顯示一段話:「請按我」,【請按我觀看範例】
透過 getElementById 取得 DOM 物件內容,並透過 getValue 連結 JavaScipt
使用 alert 將結果顯示,即可完成
相關工具
JS split method :將 DOM 物件內容取出後,再針對內容做切割
http://www.w3schools.com/jsref/jsref\_split.asp
JS RegExp Object :使用 Regular Expression 的方式,取出 DOM 之內容
http://www.w3schools.com/jsref/jsref\_obj\_regexp.asp
jsoup :用 Java 寫成的 HTML Parser
http://jsoup.org/