You are on page 1of 6

www.netskills.ac.

uk

DOM Events
Web Pages: Behaviour

CSC1014

DOM: Events
User or browser initiated Detected using event handlers
Inline with XHTML Registered in script

"Things that happen...."

Events can be programmatically invoked


Use object methods e.g.
document.getElementById('thisBox').focus() ...would cause a focus event, which could be handled by... <input type="text" name="user" id="thisBox" onfocus="runThis();" />
JISC Netskills

CSC1014

DOM: Simple (inline) event handlers


Part of XHTML specification (not script)
Attribute of element in which the event will occur
<a href="somewhere.html" onclick="runThis();">Click me</a> <h1 onmouseover="hilite('on');" onmouseout="hilite(off');">Hello</h1> <form method="post" action="somescript" onsubmit="return validation();"> ...etc... </form>

Remember XHTML is lowercase


onclick="" not onClick=""
JISC Netskills

etc...

CSC1014

DOM: Event handler registration


Event handlers can be registered within a script
No need for XHTML event handler attributes Several ways of doing this, linked to evolution of DOM Can get confusing (i.e. prepare to run into some browser differences)
function clickAlert() { alert('You clicked me!'); }

"Traditional method"
document.getElementById("goClick").onclick = clickAlert

IE "Event attachment"
document.getElementById("goClick").attachEvent('onclick',clickAlert)

W3C "advanced/standard method"


document.getElementById("goClick").addEventListener('click',clickAlert,false)

http://www.quirksmode.org/js/introevents.html
JISC Netskills

CSC1014

DOM: Ready or Loaded?


Script can be triggered to run as soon as the page has been rendered on screen (using onLoad) to ensure objects required actually exist However script access to the DOM can occur before the page is rendered on screen
Parse HTML Assemble DOM Apply CSS Start rendering screen content Finish rendering screen content
JISC Netskills

DOM is ready for scripting

Script in page contents can be processed load event occurs

CSC1014

DOM: Detecting "DOM ready"


Standard method is to add an event listener for the DOMContentLoaded event occurring for the document
document.addEventListener("DOMContentLoaded", doSomething, false)

Unfortunately IE doesn't support this

Both addEventListener and the detection of DOMContentLoaded

Workaround is to get IE to load up a (dummy) script file and tell you when that has happened

JISC Netskills

You might also like