DHTML With Javascript
DHTML With Javascript
One of the most popular uses of JavaScript is DHTML (Dynamic Hyper Text Markup Language).
DHTML is the combination of HTML and JavaScript. DHTML is using JavaScript to modify the CSS
styles of HTML elements.
DHTML is the combination of several built-in browser features in fourth generation browsers that
enable a web page to be more dynamic.
The HTML document acts as a reference to the DHTML. The DHTML can change the visibility, position,
contents, background color, z-index, clipping, size of the already positioned element. New elements can
also be added to the HTML document.
HTML DHTML
A plain page without any styles and Scripts A page with HTML, CSS, DOM and Scripts
called as HTML. called as DHTML.
HTML sites will be slow upon client-side DHTML sites will be fast enough upon client-
technologies. side technologies.
HTML stands for only static pages. It is DHTML is Dynamic HTML means HTML
referred as a static HTML and static in nature. JavaScript. Hence it is referred as a dynamic
HTML.
Components of DHTML
Dynamic HTML includes the following components: HTML, Cascading Style Sheets, Scripting and the
Document Object Model.
HTML:
HTML defines the structure of a Web page, using such basic elements as headings, forms,
tables, paragraphs and links.
Cascading Style Sheets (CSS):
A style sheet controls the formatting of HTML elements.
Style sheets are used to specify page margins, point sizes and leading.
Cascading Style Sheets is a method to determine precedence and to resolve conflicts
when multiple styles are used.
Scripting:
Scripting provides the mechanisms to interpret user actions and produce client-side changes
to a page.
DHTML can communicate with several scripting languages but JavaScript is widely used.
Document Object Model (DOM):
The DOM outlines Web page content in a way that makes it possible for HTML elements, style
sheets and scripting languages to interact with each other.
The W3C defines the DOM as a platform- and language-neutral interface that will allow programs and
scripts to dynamically access and update the content, structure, and style of documents. The
document can be further processed and the results of that processing can be incorporated back into the
presented stage.
3. Use the style attribute to put CSS code directly into a HTML element.
Advantages of CSS
Pages download faster.Less code and the pages are shorter and neater.
The look of the site is kept consistent throughout all the pages that work off the same stylesheet.
Updating the design and general site maintenance are made much easier, and errors caused by editing
multiple HTML pages occur far less often.
The ID field is most important, because id will be used to reference the positioned element.
Browsers call these positioned elements as layers.
Grouping elements in CSS:
1. <span>: The element <span> is what you could call a neutral element which does not add
anything to the document itself. But with CSS, <span> can be used to add visual features to
specific parts of text in your documents.
2. <div>:Whereas <span> is used within a block-level element as seen in the previous example,
<div> is used to group one or more block-level elements.
Object Referencing
The simplest way to reference an element in a DHTML document is by using the element’s id attribute.
The element is represented as an object, and its various XHTML attributes become properties that can be
manipulated by scripting.
Changing text using DHTML
<html>
<head>
<title>Object Model</title>
<script type = "text/javascript">
function start()
{
alert(pText.innerText);
Text.innerText = "Thanks for coming.";
}
</script>
</head>
<body onload = "start()">
<p id = "pText">Welcome to our Web page!</p>
</body>
</html>
The onload calls JavaScript start function when document loading completes. Start() displays an alert
box containing the value of pText.innerText.
The object pText refers to the p element whose id is set to pText. The innerText property of the object
refers to the text contained in that element in this example it is Welcome to our Web page!.
The start() sets the innerText property of pText to a different value. Changing the text displayed on
screen is a Dynamic HTML ability called dynamic content.
Collections all and children
Collections are arrays of related objects on a page. Collections provide an easy way of referring to any
specific element without an id.
There are several special collections in the object model. The all collection contains all the XHTML
elements in a document.
The length property of the collection specifies the size of the collection. The children collection of a
specific element contains that element’s child elements. For example, an html element has only two
children—the head element and the body element.
Object Description
Window This object represents the browser window and provides access to the document object
contained in the window. If the window contains frames, a separate window object is created
automatically for each frame, to provide access to the document rendered in that frame.
Frames are considered to be subwindows in the browser.
document This object represents the XHTML document rendered in a window.The document object
provides access to every element in the XHTMLdocument and allows dynamic modification
of the XHTML document.body This object provides access to the body element of an
XHTML document.
History This object keeps track of the sites visited by the browser user. The object provides a script
programmer with the ability to move forward and backward through the visited sites, but
for security reasons does not allow the actual site URLs to be manipulated.
navigator This object contains information about the Web browser, such as the name of the browser,
the version of the browser etc.
Location This object contains the URL of the loaded document. When this object is set to a new
URL, the browser immediately switches (navigates) to the new location.
Event This object can be used in an event handler to obtain information about the event that
occurred.
Screen The object contains information about the computer screen for the computer on which the
browser is running. Information such as the width and height of the screen in pixels can be
used to determine the size at which elements should be rendered in a Web page.
Collections Descriptions
all Many objects have an all collection that provides access to every element contained in
the object. For example, the body object’s all collection provides access to every
element in the body element of an XHTML document.
anchors This collection contains all anchor elements (a) that have a name or id attribute. The
elements appear in the collection in the order they were defined in the XHTML
document.
applets This collection contains all the applet elements in the XHTML document. Currently,
the most common applet elements are Java applets.
embeds This collection contains all the embed elements in the XHTML document.
forms This collection contains all the form elements in the XHTML document. The elements
appear in the collection in the order they were defined in the XHTML document.
frames This collection contains window objects that represent each frame in the browser
window. Each frame is treated as its own subwindow.
Dynamic Styles
An element’s style can be changed dynamically. Often such a change is made in response to user events. The
Dynamic HTML object model also allows to change the class attribute of an element—instead of changing
many individual styles at a time.
<html >
<head>
<title>Object Model</title>
<style type = "text/css">
.bigText
{
font-size: 3em;
font-weight: bold;
}
. smallText
{
font-size: .75em ;
}
</style>
<script type = "text/javascript"> function start()
{
var inputClass = prompt("Enter a className for the text " + "(bigText or smallText)", "" );
pText.className = inputClass;
}
</script>
</head>
<body onload = "start()">
<p id = "pText">Welcome to our Web site!<a
href="https://www.w3schools.com/">w3schools</a></p>
</body>
</html>
The above example contains two classes: .bigText and .smallText. The class attribute applies a style class to
an element.The class name always follows a period operator (.). Similar properties can be grouped into
one class.The property name is followed by a colon (:) and the value of that property. Multiple properties
are separated by semicolons (;).
Dynamic Positioning
In dynamic positioning, the XHTML elements can be positioned with scripting. This is done by
declaring an element’s CSS position property to be either absolute or relative, and then moving the
element by manipulating any of the top, left, right or bottom CSS properties.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Positioning</title>
<script type="text/javascript">
var speed = 5;
var count = 10;
var direction = 1;
var firstLine = "Text growing";
var fontStyle = ["serif", "sans-serif", "monospace"];
var fontStylecount = 0;
function start()
{
window.setInterval(run, 100);
}
function run()
{
var pText = document.getElementById("pText");
count += speed;
if ((count % 200) == 0) {
speed *= -1;
direction = !direction;
pText.style.color = (speed < 0) ? "red" : "blue";
firstLine = (speed < 0) ? "Text shrinking" : "Text growing";
pText.style.fontFamily = fontStyle[++fontStylecount % 3];
}
pText.style.fontSize = (count / 3) + "px";
pText.style.left = count + "px";
pText.innerHTML = firstLine + "<br /> Font size: " + (count / 3) + "px";
}
</script>
</head>
<body onload="start()">
<p id="pText" style="position: absolute; left: 0; font-family: serif; color: blue">Welcome!</p>
</body>
</html>
In the above example the position of the element is varied on the page by accessing its CSS left
attribute, scripting to vary the color, fontFamily and fontSize attributes, and the element’s innerHTML
property is used to alter the content of the element.
This function set interval takes two parameters—a function name, and how often to run that function
(in this case, every 100 milliseconds). The setTimeout() takes the same parameters but instead waits the
specified amount of time before calling the named function only once.
Frame collection
Frames are seen as collection in DHTML. Usage of frames makes the web page more interactive.
Frame.html
Cross frames
Output:
Filters and transitions
Applying filters to text and images causes changes that are persistent.Transitions are temporary
phenomena. Applying a transition allows to transfer from one page to another with a pleasant visual
effect.Filters and transitions do not add content to the pages. They just add
visual effects that work on some event.Filters and transitions are specified with the CSS filter property.
Transitions give the same kind of graphics capabilities got from presentation software like Microsoft’s
PowerPoint. Filters are applied in the style attribute. The filter property’s value is the name of the filter.
Each filter has a property named enabled. If this property is set to true, the filter is applied. If it is set to
false, the filter is not applied.
Light The light filter simulates the effect of a light < style = "filter: light”>
source shining on the page.
Filters
<html><head><title> filters</title></head><body>
<div style=”position:absolute; top:125; left:2; filter:mask”>
</div><img src="images.jfif" width=400 height=400 style="filter:invert">
</body></html>
Transitions Description Syntax
blendTrans This creates a smooth fade-in/fade- out <style=”: blendTrans( duration = 3 )">
effect. The duration determines how long
the transition takes.
revealTrans This allows the transition by using <style=” filter: revealTrans( duration =
professional-style transitions, from box 2, transition = 0 )">
out to random dissolve. The transition
parameter is the index of the element as
specified in the transition array. There
are 24 transitions.
Transitions
<html><head>
<script language=”text/javascript”>
Function blendOut()
{
f.filters(“blendTrans”).apply();
f.style visibility=”hidden”; f.filters(“blendTrans”).play();
}
</script></head>
<body><div id=” f” onClick=”blendOut()” style=”filter:blendTrans(duration=5)”>
This is a nice effect</div>
</body></html>
Data binding with tabular control
Before the advent of DHTML, the data manipulations were done on the server thus increasing the
server load and the network load. With DHTML, these manipulations can be done directly on the client
without involving the server and the network.Data binding is a process that allows an Internet user to
manipulate Web page elements using a Web browser. It employs dynamic HTML and does not require
complex scripting or programming.With data binding, data need no longer reside exclusively on the
server. The data can be maintained on the client. The data storage is well distinguished from the XHTML
markup on the page. In DHTML, larger amount of data will be sent to the client on the first request.
Changes done to the data the client side do not propagate back to the server. To bind external data to
XHTML elements, Internet Explorer employs software that iscapable of connecting the browser to live
data sources. These are known as Data Source Objects(DSOs).
Tabular Data Control
The Tabular Data Control (TDC) is an ActiveX control that is added to a page with the object
element. Data are stored in a separate file and will not be a part of the XHTML document. TDC is one
way of accessing data from DSO.
The object element will have the following properties :
Classid-specifies the TDC to be added to the page
Param tag-specifies the parameters for the object in the form of ‘name-value’ pairs.
The following are the parameters taken by TDC:
Data URL: URL of data source.
UseHeader: If this value is true, then the first line of the data file has header field.
TextQualifier: Qualifiers are characters that are placed at both the ends of a filed.
FieldDelim: Characters that act as separaters between different data fields.
Record set is the set of data from the data source. The following are the methods to access the record
set:
Methods Description
Move Next() Moves the recordset to the next row in the data source.
Move First() Moves to the first recordset in the file.
Move Last() Moves to the last recordset in the file.
Move Previous() Moves to the previous recordset in the file.
varrecordSet = Colors.recordset;
function update()
h1Title.style.color = colorRGB.innerText;
switch ( whereTo )
update();
break;
case "previous":recordSet.MovePrevious();
if ( recordSet.BOF ) recordSet.MoveLast();
update();
break;
if ( recordSet.EOF ) recordSet.MoveFirst();
update();
break;
update();
break;
</script>
input
</style>
</head>
<span style = "position: absolute; left: 200; width: 270; border-style: groove; text-align:
center;background-color: cornsilk; padding: 10">
</span><br />
<input type = "button" value = "Next" onclick = "move( 'next' );" />
<input type = "button" value = "Last" onclick = "move( 'last' );" />
</span></body></html>
Binding to an image
Many different types of XHTML elements for instance, image can be bound to data sources.Images are
binded with data set by modifying the src attribute of the image.
<imgdata src=”cat.jpeg” datafld=”image”>
The previous example, changes the color based on the recordset. Now by changing the datasrc and
datafld attribute as above will make the recordset to traverse through various images (create an image
data source). Omit the update();
Binding to a table and sorting the table data: Tables could also be binded to the data source and sorted.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: darkseagreen;
color: white;
table {
border-collapse: collapse;
width: 100%;
background-color: lightcyan;
th, td {
padding: 8px;
text-align: left;
th {
background-color: mediumslateblue;
color: white;
tr:nth-child(even) {
background-color: lightsteelblue;
caption {
margin: 10px;
font-weight: bold;
</style>
</head>
<body>
<h1>Sorting Data</h1>
<table id="colorTable">
<caption>
Sort by:
<select id="sortOptions">
</caption>
<thead>
<tr>
<th>Color Name</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<script>
// Example data, replace this with actual data from your data source
const data = [
];
function renderTable(data) {
data.forEach(item => {
row.innerHTML = `
<td>${item.ColorName}</td>
tableBody.appendChild(row);
});
function sortTable(criteria) {
let sortedData;
switch (criteria) {
case 'ColorNameAsc':
break;
case 'ColorNameDesc':
break;
case 'ColorRGBAsc':
break;
case 'ColorRGBDesc':
break;
default:
sortedData = data;
renderTable(sortedData);
sortTable(event.target.value);
});
// Initial rendering
renderTable(data);
</script>
</body>
</html>
Specify the column by which to sort in the Sort property of the TDC. This example sets property Sort
to the value of the selected option tag (this.value) when the onchange event is fired.By default, a column is
sorted in ascending order. To sort in descending order, the column name is preceded with a minus sign (-).
The Structured Graphics Control is a web interface that is used for visual presentations.The
Structured Graphics control facilitates the creation of simple shapes by using functions that
can be called via scripting or through param tags inside object elements.
The name attribute of the param tag method determines the order in which the function specified in
the value attribute is called. The distortion of shapes like translation, rotation can also be done. To provide
interaction with the user, the Structured Graphics Control can process the Dynamic HTML mouse
events onmouseup, onmousedown, onmousemove, onmouseover, onmouseout, onclick and ondblclick. By
default, the Structured Graphics Control does not capture mouse events, because doing so takes a small
amount of processing power.The Structure Graphics Control allows you to keep a set of method calls in a
separate source file and to invoke those methods by calling the SourceURL function.The following are the
functions available for Structured Graphics Control:
Function Description
SetLineColor(Rvalue, sets the color of lines and borders of shapes that are drawn. It takes an
Gvalue, Bvalue) RGB triplet in decimal notation as its three parameters.
SetLineStyle(line style, line Draws a line. A value of 1 for line style creates a solid line (the
width) default). A value of 0 does not draw any lines or borders, and a value
of 2 creates a dashed line.
SetFillColor(color) Sets the foreground color with which to fill shapes.
SetFillStyle(color style) Sets the style in which a shape is filled with color; a value of 1 fills
shapes with the solid color declared with the SetFillColor method.
Oval(x, y, height, width, Places the oval in specifies x-y location. The last parameter specifies
direction) the clockwise rotation of the oval relative to the x- axis, expressed in
degrees.
Arc(x,y,height,width,starti Draws an arc with the given parameters.
ng angle, size, rotation).
Pie(x,y,height,width,starti It fills in the arc with the foreground color, thus creating a pie shape.
ng angle, size, rotation)
Method Description
Repeat() Determines how many times the path will be traversed; setting the value to -1
specifies that the path should loop continuously
Duration() Specifies the amount of time that it takes to traverse the path, in seconds.
Bounce() When set to 1, reverses the element’s direction on the path when it reaches the
end. Setting the value to 0 returns the element to the beginning of the path
when the path has been traversed.
PolyLine() Creates a path with multiple line segments.
Target() Specifies the id of the element that is targeted by the Path Control. Setting the
CSS attribute position to absolute allows the Path Control to move an element
around the screen. Otherwise, the element would be static, locked in the position
determined by the browser when the page loads.
AddTimeMarker() The first parameter determines the point at which our time marker is placed
along the path, specified in seconds; when this point is reached, the onmarker
event is fired. The second parameter gives an identifyingname to the event,
which is later passed on to the event handler for the onmarker event. The last
parameter specifies whether to fire the onmarker event every time the object’s
path loops pastthe time marker (value=0) or to fire the event just the first time
that the time marker is passed (value= 1).
At(waiting time, This method takes two parameters: How many seconds to wait, and what action
action) to perform when that period of time has expired.