0% found this document useful (0 votes)
7 views

DHTML

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

DHTML

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Web Application Development UNIT-4

160705 DHTML

Introduction to DHTML
HTML is based on thinking of a web page like a printed page: a document that is rendered once
and that is static once rendered.

The idea behind Dynamic HTML (DHTML), however, is to make every element of a page
interactively controllable, before, during, and after the page is rendered.

This means you can make things move, appear and disappear, overlap, change styles, and
interact with the user to your heart's content.

Through DHTML, users get a more engaging and interactive web experience without constant
calls to a web server or the overhead of loading new pages, plug-ins, or large applets.

DHTML is not a language itself, but rather a combination of:

 HTML 4.0 (or XHTML 1.0)


 JavaScript -- the Web's standard scripting language
 Cascading Style Sheets (CSS) -- styles dictated outside a document's content
 Document Object Model (DOM) -- a means of accessing a document's
individual elements

Dynamic HTML presents richly formatted pages and lets you interact with the
content on those pages without having to download additional content from the
server. This means that a page can respond immediately to user actions, such as a
mouse click, without having to retrieve an entire new page from the server.

We begin by discussing the three main components of Dynamic HTML authoring:


Positioning - precisely placing blocks of content on the page and, if desired,
moving these blocks around (strictly speaking, a subset of style modifications).

Style modifications - altering the look and display of content on the page.

Event handling - how to relate user events to changes in positioning or other style
modifications.

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
Animation:

The idea behind Javascript-based animation is fairly simple; a number of DOM


elements (<img />, <div> or otherwise) are moved around the page according to
some sort of pattern determined by a logical equation or function.

To achieve the effect of animation, elements must be moved at a given interval or


frame rate; from a programming perspective, the simplest way to do this is to set
up an animation loop with a delay.

With JavaScript, it is possible to execute some code at specified time-intervals.


This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

 setInterval() - executes a function, over and over again, at specified time


intervals
 setTimeout() - executes a function, once, after waiting a specified number of
milliseconds

Syntax

window.setInterval("javascript function", milliseconds);

Below is an example that will display the current time. The setInterval() method is
used to execute the function once every 1 second, just like a digital watch.

for ex.

<p>A script on this page starts this clock:</p>

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

<script>

Var myVar=setInterval(myTimer,1000);

functionmyTimer() {

var d = new Date();


Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
document.getElementById("demo").innerHTML = d.toLocaleTimeString();

</script>

The setTimeout() Method


Syntax
window.setTimeout("javascript function", milliseconds);

Basic Animation:

Let's say that we have an object called foo which refers to a <div> element; we are
going to move this with a function that is called every 20 msec via setTimeout().

This object is within a function called doMove.

functiondoMove()

{
foo.style.left = (foo.style.left+10)+'px'; // pseudo-property code: Move right by
10px
}

doMove(); // animate the object

This will move foo 10 pixels to the right of its current position. Not bad, but this is
only one frame.

You may think a for loop would work for animation, to call this function 100
times for example, expecting to see foo to slowly move 1000px to the right - in
fact, you would see two "frames" here: the before (at 0px), and after (1000px)
because the browser is able to skip the display of items during the loop
(presumably for efficiency, or because it cannot keep up with that rate.) Therefore,

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
you need a delay. A recursive function works well here. "Move the object, and
then call this function again 20 msec from now.":

functiondoMove() {
foo.style.left = (foo.style.left+10)+'px'; // pseudo-property code: Move right by
10px
setTimeout(doMove,20); // call doMove() in 20 msec

for ex.

<script type="text/javascript">

var foo = null; // object

function doMove() {

foo.style.left = parseInt(foo.style.left)+1+'px';

setTimeout(doMove,20); // call doMove in 20msec

functioninit()

foo = document.getElementById('fooObject'); // get the "foo" object

foo.style.left = '0px'; // set its initial position to 0px

doMove(); // start animating

window.onload = init;

</script>

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
</head>

<body>

<h1>Javascript animation: Demo 1</h1>

<h2>Recursive setTimeout-based animation</h2>

<div id="fooObject" style="left: 698px;">

I am foo.

</div>

</body>

The Image() object


The Image object represents an HTML <img> element.

Creating an Image object is as simple as creating any other object in JavaScript:

varvariableName = new Image([unsigned long width, unsigned long height]);

note: width & height both are optional.

The following statement preloads the desired image:

variableName.src = "imageURL.gif";

Notice the use of the src property in the preceding statement. It enables you to
associate an actual image with an instance of the Image object.

Images on the page are represented by the Image object in JavaScript. They can be
accessed using the syntax:

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
document.images.name //access image by its name
document.images[i] //access image by its position within array
document.images.length //returns total number of images

Example:

Var myImage = new Image(100, 200);

myImage.src = 'picture.jpg';

console.log(myImage);

Result:

<img width="100" height="200" src="picture.jpg">

Loading multiple images with


arrays
In practice, you will probably need to preload more than just one image; for
example, in a menu bar containing multiple image rollovers, or if you're trying to
create a smooth animation effect. This is not difficult; all you need to do is make
use of JavaScript's arrays, as in the example below:
<script language="JavaScript">
function preloader()
{

// counter
vari = 0;

// create object
imageObj = new Image();

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
// set image list
images = new Array();
images[0]="image1.jpg"
images[1]="image2.jpg"
images[2]="image3.jpg"
images[3]="image4.jpg"

// start preloading
for(i=0; i<=3; i++)
{
imageObj.src=images[i];
}
}
</script>

In the above example, you define a variable i and an Image() object cleverly
namedimageObj. You then define a new array called images[], where each array
element stores the source of the image to be preloaded. Finally, you create a for() loop
to cycle through the array and assign each one of them to the Image() object, thus
preloading it into the cache.

In the below example we display 4 images alternatively using image array.

For ex.
<script>

varanims=new Array(4);
var frame=0;
vartimeout_states=null;
vartimerid;
functionimageload()
{
for(i=0;i<=3;i++)
{
Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
anims[i]=new Image();
anims[i].src=i+".jpg";
}
}
function animate()
{
document.ani.src=anims[frame].src;
frame++;
if(frame>3)
{
frame=0;
}
timerid=setTimeout(animate,300);
}
functioncheckButton()
{
if(document.animateform.run.value=="start")
{
document.animateform.run.value="stop";
animate();
}
else
{
document.animateform.run.value="start";

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
clearTimeout(timerid);
}
}
</script>
</head>
<body onLoad="imageload()" >
<imgsrc="0.jpg" name ="ani" height="300" width="300"/>
<form name="animateform">
<input type="button" value="start" name="run" onClick="checkButton()">
</form>
</body>
Output:

What is an Event ?

 Events are things that happen, usually user actions, that are associated with
an object.

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
 JavaScript's interaction with HTML is handled through events that occur when
the user or browser manipulates a page.
 When the page loads, that is an event. When the user clicks a button, that click,
too, is an event. Another example of events is like pressing any key, closing
window, resizing window etc.
 Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable to occur.
 Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element have a certain set of events which can trigger JavaScript Code.
 Examples of events
> click-A mouse click
> load-A web page or an image loading
> mouseover- Mousing over a hot spot on the web page
> select- Selecting an input box in an HTML form
> submit- Submitting an HTML form
> A keystroke
event handler:
 The "event handler" is a command that is used to specify actions in response to
an event.
 We can write our event handlers in Javascript of vbscript and can specify these
event handlers as a value of event tag attribute.
 An event handler executes a segment of a code based on certain events
occurring within the application, such as onLoad, onClick.
 JavaScript event handlers can be divided into two parts:

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
interactive event handlers
non-interactive event handlers
 An interactive event handler is the one that depends on the user interactivity
with the form or the document. For example, onMouseOver is an interactive
event handler because it depends on the users action with the mouse.
 On the other hand non-interactive event handler would be onLoad, because
this event handler would automatically execute JavaScript code without the
user's interactivity.
 Event handlers are embedded in documents as attributes of html tag to which
you assign JavaScript code. The syntax is:
<htmltag eventhandler=”JavaScript code”>
For ex.
<body onLoad="hello()">

 Here are all the event handlers available in JavaScript:

Event USED IN Description


Handler

onabort image Loading of an image is interrupted

onload windows, image Script runs when a HTML document loads

onunload Window, Script runs when a HTML document unloads.


User Exits the page.
Document body
onchange Select lists, text, Script runs when user changes the value of
element.
textarea
onsubmit form Script runs when the form is submitted

onreset form Script runs when the form is reset

onselect text, textarea Script runs when the form’s element is selected

onblur Window & all form Script runs when the form’s element loses focus

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
elements

onfocus Window & all form Script runs when the form’s element gets focus
elements

onkeydown Documents, images, Script runs when key is pressed


links, text areas

onkeypress Documents, images, Script runs when key is pressed and released
links, text areas

onkeyup Documents, images, Script runs when key is released


links, textareas

onclick Button, radio button, Script runs when a user click form element or link
checkbox, submit
button, reset button,
link

ondblclick Button, radio button, Script runs when a user double-click mouse
checkbox, submit
button, reset button,
link

onmousedown Documents, buttons, Script runs when mouse button is pressed


links

onmousemove Script runs when mouse pointer moves

onmouseout Area, link Script runs when mouse pointer moves out of an form’s
element

onmouseover link Script runs when mouse pointer moves over an element

onmouseup Documents, buttons, Script runs when mouse button is released


links

Error Images, windows The loading of a document or image causes an error.

onAbort:
An onAbort event handler executes JavaScript code when the user aborts loading
an image.
See Example:
<HTML>
<TITLE>Example of onAbort Event Handler</TITLE>
<HEAD>
</HEAD>
Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML

IE (older
Event chrome Firefox Safari Opera
version)

onabort Not supported Yes Not supported Not supported Not supported

<BODY>
<H3>Example of onAbort Event Handler</H3>
<b>Stop the loading of this image and see what happens:</b><p>
<IMG SRC="reaz.gif" onAbort="alert('You stopped the loading the
image!')">
</BODY>
</HTML>
Here, an alert() method is called using the onAbort event handler when the user
aborts loading the image.

onBlur:
An onBlur event handler executes JavaScript code when input focus leaves the
field of a text, textarea, or a select option. For windows, frames and framesets the
event handler executes JavaScript code when the window loses focus. In windows
you need to specify the event handler in the <BODY> attribute.

For example:
<BODY BGCOLOR='#ffffff' onBlur="document.bgcolor='#000000'">
Note: On a Windows platform, the onBlur event does not work
with <FRAMESET>.

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML

See Example:
<html>
<head>
<script type="text/javascript">
function upperCase() {
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()
}
</script>
</head>
<body>
Enter your name:
<input type="text" id="fname" onblur="upperCase()">
</body>
</html>

onFocus:
The onfocus event occurs when an element gets focus.
The onfocus event is most often used with <input>, <select>, and <a>.
In windows you need to specify the event handler in the <BODY> attribute.

For example:
<BODY BGCOLOR="#ffffff" onFocus="document.bgcolor='#000000'">

See Example:
<HTML>
<TITLE>Example of onFocus Event Handler</TITLE>
<HEAD></HEAD>
Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
<BODY>
<H3>Example of onFocus Event Handler</H3>
Click your mouse in the text box:<br>
<form name="myform">
<input type="text" name="data" value="" size=10 onFocus='alert("You
focused the textbox!!")'>
</form>
</BODY>
</HTML>

In the above example, when you put your mouse on the text box, an alert()
message displays a message.

Onchange:

The onchange event occurs when the value of an element has been changed.
For radiobuttons and checkboxes, the onchange event occurs when the checked
state has been changed.

See Example:

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

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
</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>

onClick:
The onclick event occurs when the user clicks on an element.
The onClick event handler is activated by a click on a form element. This can
mean a radio or check button, but also submit, reset, or a user-defined button. In
our example, if you click on a form element, a message should appear that tells
you which element you clicked. Here is the source code:

<html>
<head>
<title>Title of the Page</title>
<script language="JavaScript">
function message(element)
{
alert("You clicked the " + element + " element!")
}
</script>
Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
</head>
<body>
<form>
<input type="radio" name="Radio" onClick="message('Radio Button 1')">Option
1<br>
<input type="radio" name="Radio" onClick="message('Radio Button 2')">Option
2<br>
<input type="checkbox" onClick="message('Checkbutton')">Check
Button<br>
<input type="submit" value="Send" onClick="message('Send Button')">
<input type="reset" value="Reset" onClick="message('Reset Button')">
<input type="button" value="Mine" onClick="message('My very own Button')">
</form>
</body>
</html>

onLoad:
An onLoad event occurs when a window or image finishes loading. For windows,
this event handler is specified in the BODY attribute of the window. In an image,
the event handler will execute handler text when the image is loaded.
For example:
<IMG NAME="myimage" SRC="http://rhoque.com/ad_rh.jpg" onLoad="alert('You
loaded myimage')">

See Example:
<HTML>
<TITLE>Example of onLoad Event Handler</TITLE>
<HEAD>

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
<SCRIPT LANGUGE="JavaScript">
function hello()
{
alert("Hello there...\nThis is an example of onLoad.");
}
</SCRIPT>
</HEAD>
<BODY onLoad="hello()">
<H3>Example of onLoad Event Handler</H3>
</BODY>
</HTML>
The example shows how the function hello() is called by using the onLoad event
handler.

onmouseover and onmouseout:


These two event types will help you to create nice effects with images or even with
text as well. The onmouseover event occurs when you bring your mouse over any
element and the onmouseout occurs when you take your mouse out from that
element.
onMouseOver and onMouseOut are often used to create "animated" buttons.

See Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script language="JavaScript">

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
picture1=new Image
picture1.src="picture1.png"
picture2=new Image
picture2.src="picture2.png"

</script>
</head>

<body>
<a onMouseOver="document.picture.src=picture2.src"
onMouseOut="document.picture.src=picture1.src">
<img name="picture" src="picture1.png" width="146" height="73"></a>
</body>
</html>

onReset:
A onReset event handler executes JavaScript code when the user resets a form by
clicking on the reset button.

See Example:
<HTML>
<TITLE>Example of onReset Event Handler</TITLE>
<HEAD></HEAD>
<BODY>
<H3> Example of onReset Event Handler </H3>
Please type something in the text box and press the reset button:<br>
<form name="myform" onReset="alert('This will reset the form!')">
<input type="text" name="data" value="" size="20">
<input type="reset" Value="Reset Form" name="myreset">
Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
</form>
</BODY>
</HTML>
In the above example, when you push the button, "Reset Form" after typing
something, the alert method displays the message, "This will reset the form!"

onSelect:
A onSelect event handler executes JavaScript code when the user selects some of
the text within a text or textarea field.
See Example:

<HTML>
<TITLE>Example of onSelect Event Handler</TITLE>
<HEAD></HEAD>
<BODY>
<H3>Example of onSelect Event Handler</H3>
Select the text from the text box:<br>
<form name="myform">
<input type="text" name="data" value="Select This" size=20
onSelect="alert('This is an example of onSelect!!')">
</form>
</BODY>
</HTML>

In the above example, when you try to select the text or part of the text, the alert
method displays the message, "This is an example of onSelect!!".

Onsubmit:

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
Another most important event type is onsubmit. This event occurs when you try to
submit a form. So you can put your form validation against this event type.

Here is simple example showing its usage. Here we are calling a validate()
function before submitting a form data to the webserver.
If validate() function returns true the form will be submitted otherwise it will not
submit the data.

Example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

</head>
<body>
<form method="POST" name="myForm" action="mouse_over_out.html" onsubmit="return
validate()">
.......<br/>
<input type="text" name="uname"/> <br/>
<input type="submit" value="Submit" />
</form>
<script language="javascript" type="text/javascript">

function validate()
{

var x = document.forms["myForm"]["uname"].value;
if (x == null || x == "")
{
alert("Name must be filled out");
return false;
}
}
</script>
</body>
Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
</html>

Onkeypress:

Execute a JavaScript when a user presses a key:


<input type="text" onkeypress="myFunction()">

The onkeypress event occurs when the user presses a key (on the keyboard).

<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input type="text" onkeypress="myFunction()">

<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>

</body>
</html>

onkeydown Event:

Execute a JavaScript when a user is pressing a key:

<input type="text" onkeydown="myFunction()">

For ex.

<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input type="text" onkeydown="myFunction()">

<script>
Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar
Web Application Development UNIT-4
160705 DHTML
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>

</body>
</html>

onkeyup Event:

Execute a JavaScript when a user releases a key:


<input type="text" onkeyup="myFunction()">

The onkeyup event occurs when the user releases a key (on the keyboard).

<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when the user releases a key in the input field. The function
transforms the character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">

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

</body>
</html>

Prepared By:
Ankita Chauhan
CE DEPT.-MBICT
New VVnagar

You might also like