Dynamic HTML XHTML CSS

You might also like

Download as ps, pdf, or txt
Download as ps, pdf, or txt
You are on page 1of 9

Dynamic HTML

XHTML appearance CSS


Dynamic HTML content style rules

manipulate manipulate
Scripting
Language

DHTML

• A combination of technologies used to create


animated documents
• Not a W3C standard!
HTML DOM
- Originally, a marketing term used by Netscape and
Microsoft
• Using scripts, we manipulate HTML content and
style properties in reaction to events

HTML DOM DOM and JavaScript


• Combined with JavaScript, every element in the
From W3C:
HTML document is represented by an object
“A platform- and language-neutral interface that
• Elements can be manipulated using the properties
allows programs and scripts to dynamically
and methods of the corresponding objects
access and update the content and structure of
HTML and XHTML documents.” • Changes in the element properties are
immediately reflected by the browser

1
Accessing HTML Elements Accessing Elements by Paths
function execute() {
• All HTML elements (objects) are accessed var img = document.images[0]; img.src="lighton.gif"
var inx = document.forms[0].elements[0]; inx.value="xx"
through the document object
var iny = document.forms["form1"].elements["y"]; iny.value="yy"
• document itself is automatically created } head
• Several ways to access a specific element <p><img src="lightoff.gif" alt="light off" id="img1" /></p>
<form id="form1" method="get" action="nosuch"><p>
- paths in the DOM tree
<input type="text" name="x"/>
- retrieval by ID <input type="text" name="y"/>
- retrieval by tag <input type="reset"/></p>
</form> body

HTML DOM Tree Accessing Elements by ID

function execute() {
var theDiv = document.getElementById("div1");
if (theDiv.style.visibility=="hidden")
{theDiv.style.visibility="visible" }
else {theDiv.style.visibility="hidden" }
} head

<div id="div1"> This text can be hidden!</div> body

Accessing Elements by Tags Element Properties

function execute() { • Elements of different types have different sets of


var spans = document.getElementsByTagName("span");
properties and methods
spans[0].style.color="red";
spans[1].style.color="blue"; • See www.w3schools.com/htmldom/ for a
spans[1].style.fontVariant="small-caps";
detailed list of element properties and methods
} head
• Usually, all elements have the style property
<p>This <span>example</span> is lovely.</p>
• style is an object that represents the style-sheet
<p>But <span>this one</span>is even more!</p> body
rules applied over the element

2
Event Example
<html>
<head>
<title>Simple Events</title>

Events <script type="text/javascript">


function focusInput() {
var theInput = document.getElementsByTagName("input")[0]
theInput.style.background="yellow" }
function blurInput() {
theInput = document.getElementsByTagName("input")[0]
theInput.style.background="white" }
</script>
</head>

Event Example (cont) Event Model

<body> • Events usually occur due to users actions


<p>
<img src="lighton.gif" alt="light bulb" - for example, pressing the keyboard, changing a text
onmouseover="alert('Mouse Over')" /> field, moving the mouse over an element, etc.
</p>
<p> • An event is represented by an event object that is
<input type="text" onfocus="focusInput()"
created upon the event occurrence
onblur="blurInput()" />
</p> • Every event has an associated target element
</body>
</html> - For example, the image over which the mouse clicks

Event Model (cont) Inline Listener Registration

• Elements can have registered event listeners • The simplest (and most common) way to register a
associated with certain types of events listener is by adding this attribute to the element:
ontype = "JavaScript code"
• When an event takes place, the listeners that are
• For example:
registered for this event are invoked
<img src="img.gif" onmouseover="alert('!')" />
• Typically, a listener is described by a scripting
• The JavaScript code has access to the following objects:
code (e.g., JavaScript)
- this - the element (e.g., the image defined above)
- This code is executed upon listener invocation
- event - the event object

3
Some Event Types Another Example
<html>
load click reset <head><title>Event Object Example</title>
unload dblclick select <script type="text/javascript">
abort mousedown submit function execute(e) {
mousemove alert(" x: " + e.clientX + ", y: " + e.clientY +
mouseup " mouse button: " + e.button); }
keydown change
mouseover </script></head>
keypress blur
<body onmousedown="execute(event)"
keyup focus
style="cursor: pointer;
position:absolute; width:100%; height:100%"> </body>
</html>

Form Validation Form Validation - Simple Example


<html>
• In the form element, onsubmit="code" defines a
<head><title>Form Validation</title>
listener with a special functionality <script type="text/javascript">
function validate() {
• When the form is supposed to be submitted,
var theX = document.forms[0].x.value;
code is executed before submission var theY = document.forms[0].y.value;
if(theX != theY) { alert("x != y!!"); return false; }
• The code can return a Boolean value else { return true; }
- e.g., onsubmit="return function()" }
</script>
• If code returns false, submission is cancelled! </head>

Form Validation - Simple Example Form Validation - Another


(cont) Example
<body> <head><title>Form Validation</title>
<form id="email-form" action="myurl" method="get" <script type="text/javascript">
onsubmit="return validate()"> function validateEmail(form) {
<p> var emailRegExp = /^\w+\@\w+\.\w+$/;
x: <input type="text" name="x" /> var theEmail = form.email.value;
y: <input type="text" name="y" /> if(theEmail.match(emailRegExp)) { return true; }
<input type="submit" /> alert(theEmail + " is not a valid email!");
</p> return false;
</form> }
</body> </script>
</html> </head>

4
Form Validation - Another
Form Submission
Example (cont)
• A form can be submitted without the special
<body>
<form id="email-form" action="myurl" method="get" submission button
onsubmit="return validateEmail()">
<p>
• Use the function form.submit() to submit a
Name: <input type="text" name="Name:" /> <br/> specific form from JavaScript code
Email: <input type="text" name="email" />
<input type="submit" />
</p>
</form>
</body>

Mouse-Click Events Event Flow


<script type="text/javascript">
• To register a listener for the click event, use can function f1() { alert("1") }
use the onclick attribute of the element function f2() { alert("2") }
function f3() { alert("3") }
- Apply the style rule cursor:pointer to the element in </script>
order to get the pointer effect <body>
<div onclick="f1()">
• Alternatively, you can link to an JavaScript
<p onclick="f2()">
code: <img src="lighton.gif" alt="light" onclick="f3()"/>
</p>
- <a href="javascript:code">Click here</a>
</div>
</body>

Event Flow (cont) Microsoft Model

• When we click on the image, which of the functions • Event Bubbling: events propagate through the
should be executed? elements in bottom-up order
- Answer: all of them! - i.e., from the most specific to the most general
• In what order?
• Whenever an element is visited, its listeners are
• Two different models:
triggered
- Microsoft (impl. in IE)
• In our example: img → p → div
- W3C (impl. in Mozilla, Opera 7, Konqueror)

5
W3C Model Event Flow (cont)

• In the W3C model, there are two traversals: • A listener can be registered in either the capturing or the

1. Event capturing: top-down bubbling phase


• e.g., div → p → img • By default, listeners register in the bubbling phase
- So, what will be the result of the example code?
2. Event bubbling: bottom-up
• e.g., img → p → div • An element may choose to stop the flow at any listener
Element 1
execution, by calling event.stopPropagation()
- In IE: event.cancelBubble = true
Element 2

An Example Dynamic Listener Registration

• What will happen if we replace f2 with the • A listener can be dynamically registered by using
following? JavaScript code
• Microsoft:
function f2(e) {
element.ontype = functionName
alert("2");
if(e.stopPropagation) e.stopPropagation(); element.attachEvent("ontype", functionName)
if(e.cancelBubble!= undefined) e.cancelBubble=true;
• Note that the function is given as an object
}
• The function is called without arguments
• The event can be accessed using window.event

Dynamic Listener Registration


(cont)
• W3C:
element.ontype = functionName Manipulating the
element.addEventListener("type", functionName, isCapture)
Document Structure
• The function is called with event as an argument
• If isCapture is true, the listener is registered for
the capturing phase

6
Structure Manipulation DOM Tree Manipulation

• In structure manipulation, we • In this approach, we explicitly

- add/remove/replace HTML elements - create new nodes

- change the text under elements - add created nodes to the DOM tree

• Two approaches: - remove old nodes

- DOM tree manipulation (W3C specification) • To create new nodes, use these methods of document:

- Setting the innerHTML attribute (not a specification) - document.createElement("tag")


- document.createTextNode("text")
- document.createAttribute("attname")

DOM Tree Manipulation (cont) An Example

• To add and remove children of a specific element, use <html>


<head><script type="text/javascript">...</script></head>
the following methods:
<body>
- element.appendChild(newChild) <p>First Paragraph.</p>
<div id="d1"><p id="p1">Second paragraph.</p></div>
- element.insertBefore(newChild, child) <p>
<input type="button" value="replace"
- element.removeChild(child) onclick="replace(this)" />
</p>
- element.replaceChild(newChild, oldChild) </body>
</html>

An Example (cont) The innerHTML Property

function replace(button) { • The attribute innerHTML attribute of an element


d = document.getElementById("d1");
p = document.getElementById("p1"); is the HTML code embedded inside that element
h = document.createElement("h1"); • Hence, you can replace existing content by
text = document.createTextNode("This is a header.");
h.appendChild(text); setting this attribute:
- element.innerHTML = "new HTML code"
d.replaceChild(h,p);
• Not recognized by W3C specifications, but
button.disabled=true;
} supported by Web browsers

7
Previous Example with
innerHTML

function replace(button) {
d = document.getElementById("d1");
The window Object
d.innerHTML = "<h1>This is a header<\/h1>";

button.disabled=true;
}

The window Object Dialog Boxses

• Built-in object called window • alert("warning!!!");


• Represents the browser window of the document • confirm("are you sure?");
• Several window objects may co-exist - returned value is Boolean
- Separate windows/tabs
• prompt("enter your name");
- Separate frames
- returned value is either a string
• Default object – need not specify window to access its
or a null object
properties and methods
- window.alert() and alert() are the same
Rendering stops until box closure!

An Example The location Object

<script type="text/javascript"> • The object window.location represents the current URL


of the window
alert("You are about to start");
document.write("Started<br/>"); • For example:
- location.href - the current URL (can be changed!)
conf = confirm("Should I continue?");
if(conf) { - location.hostname
name = prompt("Enrer your name") - location.pathname
document.write("Your name is " + name +.<br/>");
} • Also has methods:
</script> - location.reload(),
- location.replace(‘URL’)

8
Opening New Windows Accessing Window Frames

• window.open("URL") - opens URL in a new • window.top - the topmost window


window • window.frames - a collection of the frames in
- you can specify other properties, like size, is the window
resizable, etc.
• In one frame, use window.top.frames[i] to get to
- returns the new window object
another frame

The navigator Object The history Object

• The object window.navigator contains • The object window.history contains information


information about the browser about window’s navigation history
• For example: • For example:
- navigator.appName - the name of the browser - history.back() - same as clicking the back button
- navigator.appVersion - the version of the browser - history.forward() - same as clicking the forward
- navigator.cookieEnabled button

- navigator.platform - the OS name - history.go(i) - go forward i times


• If i is negative, go back -i times

You might also like