DOM-events

 

一、在Html的事件裡可以放入要執行的JavaScript code

<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>

 

二、如果要自己改變自己的property可使用this

<button onclick="this.innerHTML=Date()">The time is?</button>

 

三、一些Html常用的事件

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

 

四、於Script裡面寫觸發事件,而Html裡面的內容可以不指定event handle

<!DOCTYPE html>
<html>
<head>
</head>
<body>

    <p>Click "Try it" to execute the displayDate() function.</p>

    <button id="myBtn">Try it</button>

    <p id="demo"></p>

    <script>
        document.getElementById("myBtn").onclick = function () { displayDate() };

        function displayDate() {
            document.getElementById("demo").innerHTML = Date();
        }
    </script>

</body>
</html>

 

五、在onload時執行function-checkCookies()

<!DOCTYPE html>
<html>
<body onload="checkCookies()">

    <p id="demo"></p>

    <script>
        function checkCookies() {
            var text = "";
            if (navigator.cookieEnabled == true) {
                text = "Cookies are enabled.";
            } else {
                text = "Cookies are not enabled.";
            }
            document.getElementById("demo").innerHTML = text;
        }
    </script>

</body>
</html>

 

六、當資料輸入完畢確認後做onchange時

<!DOCTYPE html>
<html>
<head>
    <script>
        function myFunction() {
            var x = document.getElementById("fname");
            x.value = x.value.toUpperCase();
        }
    </script>
</head>
<body>

    Enter your name: <input type="text" id="fname" onchange="myFunction()">
    <p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>

</body>
</html>

 

七、還有滑鼠的onmouseover、onmouseout與onmouseup、onmousedown事件

<!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>
<!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>

 

八、HTML DOM Events參考資料

DOM: Indicates in which DOM Level the property was introduced.

Mouse Events

Event Description DOM
onclick The event occurs when the user clicks on an element 2
oncontextmenu The event occurs when the user right-clicks on an element to open a context menu  
ondblclick The event occurs when the user double-clicks on an element 2
onmousedown The event occurs when a user presses a mouse button over an element 2
onmouseenter The event occurs when the pointer is moved onto an element 2
onmouseleave The event occurs when the pointer a user moves the mouse pointer out of an element 2
onmousemove The event occurs when the pointer is moving while it is over an element 2
onmouseover The event occurs when the pointer is moved onto an element, or onto one of its children 2
onmouseout The event occurs when a user moves the mouse pointer out of an element, or out of one of its children 2
onmouseup The event occurs when a user releases a mouse button over an element 2

Keyboard Events

Event Description DOM
onkeydown The event occurs when the user is pressing a key 2
onkeypress The event occurs when the user presses a key 2
onkeyup The event occurs when the user releases a key 2

Frame/Object Events

Event Description DOM
onabort The event occurs when the loading of a resource has been aborted 2
onbeforeunload The event occurs before the document is unloaded 2
onerror The event occurs when an error occurs while loading an external file 2
onhashchange The event occurs when there has been changes to the anchor part of the current URL  
onload The event occurs when an object has loaded 2
onresize The event occurs when a document view is resized 2
onscroll The event occurs when an element's scrollbar is being scrolled 2
onunload The event occurs once a page has unloaded (for <body>) 2

Form Events

Event Description DOM
onblur The event occurs when an element loses focus 2
onchange The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <keygen>, <select>, and <textarea>) 2
onfocus The event occurs when an element gets focus 2
onfocusin The event occurs when an element is about to get focus 2
onfocusout The event occurs when an element is about to lose focus 2
oninput The event occurs when an element gets user input 3
oninvalid The event occurs when an element is invalid  
onreset The event occurs when a form is reset 2
onsearch The event occurs when a user writes something in a search field (for <input="search">)  
onselect The event occurs after the user selects some text (for <input> and <textarea>) 2
onsubmit The event occurs when a form is submitted 2

Drag Events

Event Description DOM
ondrag The event occurs when an element is being dragged  
ondragend The event occurs when the user has finished dragging an element  
ondragenter The event occurs when the dragged element enters the drop target  
ondragleave The event occurs when the dragged element leaves the drop target  
ondragover The event occurs when the dragged element is over the drop target  
ondragstart The event occurs when the user starts to drag an element  
ondrop The event occurs when the dragged element is dropped on the drop target  

Clipboard Events

Event Description DOM
oncopy The event occurs when the user copies the content of an element  
oncut The event occurs when the user cuts the content of an element  
onpaste The event occurs when the user pastes some content in an element  

Print Events

Event Description DOM
onafterprint The event occurs when a page has started printing, or if the print dialogue box has been closed  
onbeforeprint The event occurs when a page is about to be printed  

Media Events

Event Description DOM
onabort The event occurs when the loading of an audio/video is aborted  
oncanplay The event occurs when the browser can start playing the audio/video  
oncanplaythrough The event occurs when the browser can play through the audio/video without stopping for buffering  
ondurationchange The event occurs when the duration of the audio/video is changed  
onemptied The event occurs when the current playlist is empty  
onended The event occurs when the audio/video has ended  
onerror The event occurs when an error occurred during the loading of an audio/video  
onloadeddata The event occurs when the browser has loaded the current frame of the audio/video  
onloadedmetadata The event occurs when the browser has loaded meta data for the audio/video  
onloadstart The event occurs when the browser starts looking for the audio/video  
onpause The event occurs when the audio/video has been paused  
onplay The event occurs when the audio/video has been started or is no longer paused  
onplaying The event occurs when the audio/video is ready to play after having been paused or stopped for buffering  
onprogress The event occurs when the browser is downloading the audio/video  
onratechange The event occurs when the playing speed of the audio/video is changed  
onseeked The event occurs when the user is finished moving/skipping to a new position in the audio/video  
onseeking The event occurs when the user starts moving/skipping to a new position in the audio/video  
onstalled The event occurs when the browser is trying to get media data, but data is not available  
onsuspend The event occurs when the browser is intentionally not getting media data  
ontimeupdate The event occurs when the current playback position has changed  
onvolumechange The event occurs when the volume has been changed  
onwaiting The event occurs when the video stops because it needs to buffer the next frame  

Animation Events

Event Description DOM
animationend The event occurs when a CSS animation has completed  
animationiteration The event occurs when a CSS animation is repeated  
animationstart The event occurs when a CSS animation has started  

Transition Events

Event Description DOM
transitionend The event occurs when a CSS transition has completed  

Misc Events

Event Description DOM
onmessage The event occurs when a message is received through or from an object (WebSocket, Web Worker, Event Source or a child frame or a parent window)  
ononline The event occurs when the browser starts to work online  
onoffline The event occurs when the browser starts to work offline  
onpopstate The event occurs when the window's history changes  
onshow The event occurs when a <menu> element is shown as a context menu  
onstorage The event occurs when a Web Storage area is updated  
ontoggle The event occurs when the user opens or closes the <details> element  
onwheel The event occurs when the wheel button of a mouse rolls  

Event Object

Constants

Constant Description DOM
CAPTURING_PHASE The current event phase is the capture phase (3) 1
AT_TARGET The current event is in the target phase, i.e. it is being evaluated at the event target (1) 2
BUBBLING_PHASE The current event phase is the bubbling phase (2) 3

Properties

Property Description DOM
bubbles Returns whether or not an event is a bubbling event 2
cancelable Returns whether or not an event can have its default action prevented 2
currentTarget Returns the element whose event listeners triggered the event 2
eventPhase Returns which phase of the event flow is currently being evaluated 2
target Returns the element that triggered the event 2
timeStamp Returns the time (in milliseconds relative to the epoch) at which the event was created 2
type Returns the name of the event 2

Methods

Method Description DOM
initEvent() Specifies the event type, whether or not the event can bubble, whether or not the event's default action can be prevented 2
preventDefault() To cancel the event if it is cancelable, meaning that any default action normally taken by the implementation as a result of the event will not occur 2
stopPropagation() To prevent further propagation of an event during event flow 2

EventTarget Object

Methods

Method Description DOM
addEventListener() Allows the registration of event listeners on the event target (IE8 = attachEvent()) 2
dispatchEvent() Allows to send the event to the subscribed event listeners (IE8 = fireEvent()) 2
removeEventListener() Allows the removal of event listeners on the event target (IE8 = detachEvent()) 2

EventListener Object

Methods

Method Description DOM
handleEvent() Called whenever an event occurs of the event type for which the EventListener interface was registered 2

DocumentEvent Object

Methods

Method Description DOM
createEvent()   2

MouseEvent/KeyboardEvent Object

Properties

Property Description DOM
altKey Returns whether or not the "ALT" key was pressed when an event was triggered 2
button Returns which mouse button was clicked when an event was triggered 2
clientX Returns the horizontal coordinate of the mouse pointer, relative to the current window, when an event was triggered 2
clientY Returns the vertical coordinate of the mouse pointer, relative to the current window, when an event was triggered 2
ctrlKey Returns whether or not the "CTRL" key was pressed when an event was triggered 2
keyIdentifier Returns the identifier of a key 3
keyLocation Returns the location of the key on the device 3
metaKey Returns whether or not the "meta" key was pressed when an event was triggered 2
relatedTarget Returns the element related to the element that triggered the event 2
screenX Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered 2
screenY Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered 2
shiftKey Returns whether or not the "SHIFT" key was pressed when an event was triggered 2

Methods

Method Description W3C
initMouseEvent() Initializes the value of a MouseEvent object 2
initKeyboardEvent() Initializes the value of a KeyboardEvent object 3

 

參考資料:

HTML DOM Events

Events-Event Object

Interfaces based on Event

EventTarget

window.onload

重新認識 JavaScript 番外篇 (6) - 網頁的生命週期