Dynamic Web Documents with JavaScript
Dynamic Web Documents with JavaScript
(24BECSE304)
Module 4
Topics: Dynamic Documents with JavaScript & Welcome to
React
PREPARED BY:
Prof. Shruthi V Kulkarni
Assistant Professor
Dept. of CSE, SNPSU
Web Technology 24BECSE304
Module 4
Chapter 1
Dynamic Documents with JavaScript
Introduction
DHTML is not a new markup language. It is a collection of technologies that allow dynamic changes to
HTML documents. Enables modification of:
Tag attributes
Tag contents
Element style properties
Changes occur after the document has been loaded and is still being displayed. Triggered by:
User interaction (e.g., clicking a button, hovering over text)
Browser events (e.g., page load, resize)
Implemented using:
Embedded scripts (JavaScript)
Accessing HTML elements via the DOM (Document Object Model)
Browser Support for DHTML is not uniform across browsers & this discussion follows W3C-standard
approaches (not vendor-specific features).
Positioning Elements
Early web design offered little control over the placement of HTML elements. Elements were arranged
sequentially (like in a word processor): Fill a row → Start a new row → fill it → so on.
CSS-P (Cascading Style Sheets – Positioning) was released by W3C in 1997 with a purpose of Precise
control over element positioning & has browser Support : IE8, IE9, Firefox 3, Chrome 12 (full support).
CSS-P allows positioning of any element anywhere on a web page display. It also supports
dynamic repositioning of elements using JavaScript by changing positioning-related style
properties.
1. left – Specifies the distance from the left reference point to the element’s position.
2. top – Specifies the distance from the top reference point to the element’s position.
3. position – Works with left and top to control placement and movement.
o Values:
absolute – Positions the element exactly relative to its first positioned ancestor.
relative – Positions the element relative to its normal position.
static – Default value; elements are positioned according to the normal flow of the
page.
Dynamic Movement:
With JavaScript, you can change left and top values in real time, enabling animation or interaction.
Absolute Positing
Absolute positioning places an element at a specific location on the page, ignoring the positions of other
elements. Coordinates are defined relative to the nearest positioned ancestor (or the document body if
none exists).
Syntax:
-- text --
</p>
Where,
position: absolute; → enables absolute positioning.
left: 100px; → places the element 100 pixels from the left edge of the containing element/window.
top: 200px; → places the element 200 pixels from the top edge of the containing element/window.
Key Uses:
1. Fixed Placement
o Used when you want an element in an exact position regardless of surrounding content.
2. Layering Elements
o Can be used to superimpose text over other elements, such as creating a watermark
effect.
Special text (e.g., a subliminal message) can be placed over a normal paragraph:
em is a relative unit.
Size is relative to the parent element’s font size.
Ensures text scales proportionally in nested elements.
For example, a paragraph of normal text that describes apples is displayed. Superimposed on this
paragraph is the somewhat subliminal message “APPLES ARE GOOD FOR YOU”. Here is the
document: [Link]
<!DOCTYPE html>
<!-- [Link]
Illustrates absolute positioning of elements
-->
<html lang = "en">
<head>
<title> Absolute positioning </title>
<meta charset = "utf-8" />
<style type = "text/css">
/* A style for a paragraph of text */
.regtext {font-family: Times; font-size: 1.2em; width: 500px}
/* A style for the text to be absolutely positioned */
.abstext {position: absolute; top: 25px; left: 25px;
font-family: Times; font-size: 1.9em;
font-style: italic; letter-spacing: 1em;
color: rgb(160,160,160); width: 450px}
</style>
</head>
<body>
<p class = "regtext">
Apple is the common name for any tree of the genus Malus,
of the family Rosaceae. Apple trees grow in any of the
temperate areas of the world. Some apple blossoms are white,
but most have stripes or tints of rose. Some apple blossoms
are bright red. Apples have a firm and fleshy structure that
grows from the blossom. The colors of apples range from
green to very dark red. The wood of apple trees is fine
grained and hard. It is, therefore, good for furniture
construction. Apple trees have been grown for many
centuries. They are propagated by grafting because they
do not reproduce themselves.
<span class = "abstext">
APPLES ARE GOOD FOR YOU
</span>
</p>
</body></html>
Display of [Link]
To illustrate the placement of nested elements, the document [Link] is modified to place the regular
text 100 pixels from the top and 100pixels from the left. The special text is nested inside the regular text
by using <div> and <span> tags. The modified document, which is named [Link], is as follows:
<!DOCTYPE html>
<!-- [Link]
Illustrates nested absolute positioning of elements
-->
<html lang = "en">
<head>
<title> Nested absolute positioning </title>
<meta charset = "utf-8" />
<style type = "text/css">
/* A style for a paragraph of text */
.regtext {font-family: Times; font-size: 1.2em; width: 500px;
position: absolute; top: 100px; left: 100px;}
/* A style for the text to be absolutely positioned */
.abstext {position: absolute; top: 25px; left: 25px;
font-family: Times; font-size: 1.9em;
font-style: italic; letter-spacing: 1em;
color: rgb(160,160,160); width: 450px;}
</style>
</head>
<body>
<p class = "regtext">
Apple is the common name for any tree of the genus Malus,
of the family Rosaceae. Apple trees grow in any of the
temperate areas of the world. Some apple blossoms are white,
but most have stripes or tints of rose. Some apple blossoms
are bright red. Apples have a firm and fleshy structure that
grows from the blossom. The colors of apples range from
green to very dark red. The wood of apple trees is fine
grained and hard. It is, therefore, good for furniture
construction. Apple trees have been grown for many
centuries. They are propagated by grafting because they
do not reproduce themselves.
<span class = "abstext">
APPLES ARE GOOD FOR YOU
</span>
</p>
</body>
</html>
Display of [Link]
Relative Positioning:
Relative positioning means an element is placed relative to its natural position in the document's flow.
When you use relative positioning, an element is positioned relative to where it would regularly be. If the
top and left properties are given, then relative positioning displace the element by the specified amount
from the natural position. If the top and left properties are not specified then element is positioned as if
like the it is statically positioned. However, such an element can be moved later. Relative positioning is
used for creating different effects in the document. It can be used to highlight the special words in the
text. The following example highlight the word “good” in line of text.
[Link]
<!DOCTYPE html>
<!-- [Link]
Illustrates relative positioning of elements
-->
<html lang = "en">
<head>
<title> Relative positioning </title>
<meta charset = "utf-8" />
<style type = "text/css">
.regtext {font: 2em Times}
.spectext {font: 2em Times; color: red; position: relative;
top: 15px;}
</style>
</head>
<body>
<p class = "regtext">
Apples are
<span class = "spectext"> GOOD </span> for you.
</p>
</body></html>
Display of [Link]
Relative positioning can be used to create superscripts. For example, the following can be used to place
“xyz” 10 pixels above the natural baseline of the text.
<p> The superscript in this name <span style=”position: relative; top:-3px”> xyz</span> is “xyz”. </p>
Static Positioning:
'Static' positioning is identical to normally rendered HTML. These elements cannot be positioned or
repositioned, nor do they define a coordinate system for child elements. This is the default value for
'position', except for the <BODY> element, which, while it cannot be positioned, does define a coordinate
system for child elements.
Moving Elements:
Movement Mechanism:
Change the top or left property values.
Absolute positioning → Element moves directly to the new top and left coordinates (relative
to its containing block).
Relative positioning → Element moves from its original position by the given distances.
Setup:
Process:
HTML elements with position set to absolute or relative can be moved. Style is used in DOM to change
top and left because these are CSS style properties. Input from text boxes → string representation of
numbers. top and left properties require unit abbreviations (e.g., "px"). JavaScript concatenates "px" to
the numeric input before assignment.
This document, called [Link], and the associated JavaScript file, [Link], are as follows:
<!DOCTYPE html>
<!-- [Link]
Uses [Link] to move an image within a document
-->
<html lang = "en">
<head>
<title> Moving elements </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
</head>
<body>
<form action = "">
<p>
<label>
x coordinate:
<input type = "text" id = "leftCoord" size = "3" />
</label>
<br />
<label>
y coordinate:
<input type = "text" id = "topCoord" size = "3" />
</label>
<br />
<input type = "button" value = "Move it"
onclick =
"moveIt('saturn',
[Link]('topCoord').value,
[Link]('leftCoord').value)" />
</p>
</form>
<div id = "saturn" style = "position: absolute;
top: 115px; left: 0;">
<img src = "../images/[Link]"
alt = "(Picture of Saturn)" />
</div>
</body>
</html>
// [Link]
// Illustrates moving an element within a document
// The event handler function to move an element
function moveIt(movee, newTop, newLeft) {
dom = [Link](movee).style;
// Change the top and left properties to perform the move
// Note the addition of units to the input values
[Link] = newTop + "px";
[Link] = newLeft + "px";
Element Visibility
Document elements can be specified to be visible or hidden with the values if their visibility property.
The two possible values for the visibility are – visible and hidden.
[Link]
<!DOCTYPE html>
<!-- [Link]
Uses [Link]
Illustrates visibility control of elements
-->
<html lang = "en">
<head>
<title> Visibility control </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
</head>
<body>
<form action = "">
<div id = "saturn" style = "position: relative;
visibility: visible;">
<img src = "../images/[Link]"
alt = "(Picture of Saturn)" />
</div>
<p>
<br />
<input type = "button" value = "Toggle Saturn"
onclick = "flipImag()" />
</p>
</form>
</body>
</html>
// [Link]
// Illustrates visibility control of elements
// The event handler function to toggle the visibility
// of the images of Saturn
function flipImag() {
dom = [Link]("saturn").style;
// Flip the visibility adjective to whatever it is not now
if ([Link] == "visible")
[Link] = "hidden";
else
[Link] = "visible";
}
The background and foreground colors of the document display and font properties of the text
can be changed dynamically
Changing Colors:
Dynamic changes to colors are relatively simple. In the next example, the user is presented with two text
boxes into which color specifications can be typed—one for the document background color and one for
the foreground color.
The colors can be specified in any of the three ways that color properties can be given in CSS. A JavaScript
function that is called whenever one of the text boxes is changed makes the change in the document’s
appropriate color property: backgroundColor or color.
The first of the two parameters to the function specifies whether the new color is for the background or
foreground; the second specifies the new color. The new color is the value property of the text box that
was changed by the user.
In this example, the calls to the handler functions are in the HTML text box elements. This approach
allows a simple way to reference the element’s DOM address.
The JavaScript this variable in this situation is a reference to the object that represents the element in
which it is referenced. A reference to such an object is its DOM address.
Therefore, in a text element, the value of this is the DOM address of the text element. So, in the
example, [Link] is used as an actual parameter to the handler function. Because the call is in an input
element, [Link] is the DOM address of the value of the input element.
This document, called [Link], and the associated JavaScript file are as follows:
<!DOCTYPE html>
<!-- [Link]
Uses [Link]
Illustrates dynamic foreground and background colors
-->
<html lang = "en">
<head>
<title> Dynamic colors </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
</head>
<body>
<p style = "font-family: Times; font-style: italic;
font-size: 2em;" >
This small page illustrates dynamic setting of the
foreground and background colors for a document
</p>
<form action = "">
<p>
<label>
Background color:
// [Link]
// Illustrates dynamic foreground and background colors
// The event handler function to dynamically set the
// color of background or foreground
function setColor(where, newColor) {
if (where == "background")
[Link] = newColor;
else
[Link] = newColor;
}
Changing Fonts:
Web users are accustomed to having links in documents change color when the cursor is placed over
them. Any property of a link can be changed by using the mouse event, ‘ mouseover ‘ to trigger JavaScript
event handlers. Thus the font style and font size, as well as the color, can be changed when the cursor is
placed over a link.
The link can be changed back to its original form when an event handler is triggered with the ‘ mouseout
‘event. In the following example, the only element is a sentence with an embedded link. The foreground
color for the document is the default black. The link is presented in blue. When the mouse cursor is placed
over the link, its color changes to red and its font style changes to italic.
[Link]
<!DOCTYPE html>
<!-- [Link]
Illustrates dynamic font styles and colors
-->
<html lang = "en">
<head>
<title> Dynamic fonts </title>
<meta charset = "utf-8" />
<style type = "text/css">
Display of [Link] with the mouse cursor not over the word
Dynamic Content
Dynamic changes can be made not only to position, visibility, colors, and styles of elements, but
also to the content inside them.
Content changes are done through the value property of the associated JavaScript object.
Changing content is conceptually similar to changing style properties.
Purpose: Assist users while filling out forms by providing contextual help in a dedicated text
area (help box).
Behavior:
o When the mouse cursor is placed over an input field → help box shows specific guidance
for that field.
o When the cursor moves away from all input fields → help box reverts to a default
message (“assistance is available”).
JavaScript Array: Stores all help messages for different fields.
Events Used:
1. mouseover → Calls a handler function to change help box content to the relevant message.
2. mouseout → Calls a handler function to revert content to the standard default message.
Handler Function:
o Receives a parameter that specifies which message to display.
o Updates the help box content dynamically.
[Link]
<!DOCTYPE html>
<!-- [Link]
Illustrates dynamic values
-->
<html lang = "en">
<head>
<title> Dynamic values </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
<style type = "text/css">
textarea {position: absolute; left: 250px; top: 0px;}
span {font-style: italic;}
p {font-weight: bold;}
</style>
</head>
<body>
<form action = "">
<p>
<span>
Customer information
</span>
<br /><br />
<label>
Name:
<input type = "text" onmouseover = "messages(0)"
onmouseout = "messages(4)" />
</label>
<br />
<label>
Email:
<input type = "text" onmouseover = "messages(1)"
onmouseout = "messages(4)" />
</label>
<br /> <br />
<span>
To create an account, provide the following:
</span>
<br /> <br />
<label>
User ID:
<input type = "text" onmouseover = "messages(2)"
onmouseout = "messages(4)" />
</label>
<br />
<label>
Password:
<input type = "password"
onmouseover = "messages(3)"
onmouseout = "messages(4)" />
</label>
<br />
</p>
<textarea id = "adviceBox" rows = "3" cols = "50">
This box provides advice on filling out the form
on this page. Put the mouse cursor over any input
field to get advice.
</textarea>
<br /><br />
<input type = "submit" value = "Submit" />
<input type = "reset" value = "Reset" />
</form>
</body>
</html>
// [Link]
// Illustrates dynamic values
var helpers = ["Your name must be in the form: \n \
first name, middle initial., last name",
"Your email address must have the form: \
user@domain",
"Your user ID must have at least six characters",
"Your password must have at least six \
characters and it must include one digit",
"This box provides advice on filling out\
the form on this page. Put the mouse cursor over any \
input field to get advice"]
// ***********************************************************
// The event handler function to change the value of the
// textarea
function messages(adviceNumber) {
[Link]("adviceBox").value =
helpers[adviceNumber];
}
Display of [Link]
Stacking Elements
The top and left properties used to place an element anywhere within the two-dimensional display of a
document. These values define vertical and horizontal positioning. Although the browser display is two-
dimensional, a third dimension effect can be created using stacked elements. Similar to stacking windows
in a graphical user interface. Multiple elements can occupy the same space. Only one element (the top
one) is visible in the overlapping area.
z-index attribute determines which element appears on top in overlapping situations. Higher z-index value
→ element displayed above elements with lower z-index.
JavaScript equivalent property: [Link]. Used to bring elements forward or send them back in the
stacking order.
[Link]
<!DOCTYPE html>
<!-- [Link]
Uses [Link]
Illustrates dynamic stacking of images.
-->
<html lang = "en">
<head>
<title> Dynamic stacking of images </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
<style type = "text/css">
.plane1 {position: absolute; top: 0; left: 0;
z-index: 0;}
.plane2 {position: absolute; top: 50px; left: 110px;
z-index: 0;}
.plane3 {position: absolute; top: 100px; left: 220px;
z-index: 0;}
</style>
</head>
<body>
<p>
<img class = "plane1" id = "airplane1"
src = "../images/[Link]"
alt = "(Picture of an airplane)"
onclick = "toTop('airplane1')" />
<img class = "plane2" id = "airplane2"
src = "../images/[Link]"
alt = "(Picture of an airplane)"
onclick = "toTop('airplane2')" />
<img class = "plane3" id = "airplane3"
src = "../images/[Link]"
alt = "(Picture of an airplane)"
onclick = "toTop('airplane3')" />
</p>
</body>
</html>
// [Link]
// Illustrates dynamic stacking of images
var topp = "airplane1";
// The event handler function to move the given element
// to the top of the display stack
function toTop(newTop) {
// Set the two dom addresses, one for the old top
// element and one for the new top element
domTop = [Link](topp).style;
domNew = [Link](newTop).style;
// Set the zIndex properties of the two elements, and
// reset topp to the new top
[Link] = "0";
[Link] = "10";
topp = newTop;
}
The display of [Link] after clicking the second image (photographs courtesy of Cessna
Aircraft Company)
The display of [Link] after clicking the bottom image (photographs courtesy of Cessna
Aircraft Company)
If you click somewhere on the page, that click is a special kind of event called a MouseEvent. Along
with other information, it tells you where you clicked in two different ways:
The trick is in passing the event object to the JavaScript function that handles the click.
When you click, the browser automatically creates the event object.
In Firefox, this object is handed directly to your function if you list it as a parameter.
In Chrome and Internet Explorer, the object exists as a global variable meaning it’s just “there”
without you asking for it.
One interesting note about the preceding cursor-finding example is that, with IE and Chrome, the mouse
clicks are ignored if the mouse cursor is below the last element on the display. The FX browser always
responds the same way, regardless of where the cursor is on the display.
[Link]
<!DOCTYPE html>
<!-- [Link]
Uses [Link]
Illustrates x- and y-coordinates of the mouse cursor
-->
<html lang = "en">
<head>
<title> Where is the cursor? </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
</head>
<body onclick = "findIt(event)">
<form action = "">
<p>
Within the client area: <br />
x:
<input type = "text" id = "xcoor1" size = "4" />
y:
<input type = "text" id = "ycoor1" size = "4" />
<br /><br />
Relative to the origin of the screen coordinate system:
<br />
x:
<input type = "text" id = "xcoor2" size = "4" />
y:
<input type = "text" id = "ycoor2" size = "4" />
</p>
</form>
<p>
<img src = "../images/[Link]" alt = "(Picture of an
airplane)" />
</p>
</body>
</html>
// [Link]
// Show the coordinates of the mouse cursor position
// in an image and anywhere on the screen when the mouse
// is clicked
// The event handler function to get and display the
// coordinates of the cursor, both in an element and
// on the screen
function findIt(evt) {
[Link]("xcoor1").value = [Link];
[Link]("ycoor1").value = [Link];
[Link]("xcoor2").value = [Link];
[Link]("ycoor2").value = [Link];
}
Display of [Link] (the cursor was in the tail section of the plane)
Left offset: -130 pixels → Moves the message horizontally to center it over the cursor.
Top offset: -25 pixels → Moves the message vertically to center it.
IE & Chrome:
The message only appears if the click happens within a specific part of the display defined
by <br> elements.
Firefox:
A click anywhere on the screen will trigger the display of the message.
[Link]
<!DOCTYPE html>
<!-- [Link]
Uses [Link]
Display a message when the mouse button is pressed,
no matter where it is on the screen
-->
<html lang = "en">
<head>
<title> Sense events anywhere </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
</head>
<body onmousedown = "displayIt(event);"
onmouseup = "hideIt();">
<p>
<span id= "message"
style = "color: red; visibility: hidden;
position: relative;
font-size: 1.7em; font-style: italic;
font-weight: bold;">
Please don't click here!
</span>
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
</p>
</body>
</html>
// [Link]
// Display a message when the mouse button is pressed,
// no matter where it is on the screen
// The event handler function to display the message
function displayIt(evt) {
var dom = [Link]("message");
[Link] = ([Link] - 130) + "px";
[Link] = ([Link] - 25) + "px";
[Link] = "visible";
}
// ****************************************************
// The event handler function to hide the message
function hideIt() {
[Link]("message").[Link] =
"hidden";
}
Instant movement is done by changing top and left properties directly. Slow movement is achieved
by:
Moving the element in small steps.
Adding short delays between each step.
a) setTimeout()
Executes code once after a specified delay (in milliseconds).
Syntax: setTimeout("mover()", 20);
→ Calls mover() after 20 milliseconds.
b) setInterval()
Executes code repeatedly at a set interval.
Two forms:
1. Two parameters:
Code (string or function name)
Interval (milliseconds)
2. Multiple parameters:
Function name (not as a string)
Interval (milliseconds)
Additional parameters to pass to the function
Initial Setup
Text is placed in a <span> element at (100, 100).
CSS position values are strings like "100px". Must remove "px" to do arithmetic. Use numeric-only
strings to allow automatic type conversion to numbers. After calculations, concatenate "px" back before
setting [Link] and [Link]. Placing JavaScript in a separate .js file prevents HTML
comment issues.
Example issue:
If JavaScript is inside HTML comments and contains -- (like x--;), HTML validators may flag it as
an invalid comment.
[Link]
<!DOCTYPE html>
<!-- [Link]
Uses [Link]
Illustrates a moving text element
-->
<html lang = "en">
<head>
<title> Moving text </title>
<meta charset = "utf-8" />
<script type = "text/javascript"
src = "[Link]">
</script>
</head>
<!-- Call the initializing function on load, giving the
destination coordinates for the text to be moved
-->
<body onload = "initText()">
<!-- The text to be moved, including its initial position -->
<p>
<span id = 'theText' style =
"position: absolute; left: 100px; top: 100px;
[Link]
//***********************************************************
// This is [Link] - used with [Link]
var dom, x, y, finalx = 300, finaly = 300;
// ************************************************* //
// A function to initialize the x- and y-coordinates
// of the current position of the text to be moved
// and then call the mover function
function initText() {
dom = [Link]('theText').style;
/* Get the current position of the text */
var x = [Link];
var y = [Link];
/* Convert the string values of left and top to
numbers by stripping off the units */
x = [Link](/\d+/);
y = [Link](/\d+/);
/* Call the function that moves it */
moveText(x, y);
} /*** end of function initText */
// ************************************************* //
// A function to move the text from its original
// position to (finalx, finaly)
function moveText(x, y) {
/* If the x-coordinates are not equal, move
x toward finalx */
if (x != finalx)
if (x > finalx) x--;
else if (x < finalx) x++;
/* If the y-coordinates are not equal, move
y toward finaly */
if (y != finaly)
if (y > finaly) y--;
else if (y < finaly) y++;
/* As long as the text is not at the destination,
call the mover with the current position */
if ((x != finalx) || (y != finaly)) {
/* Put the units back on the coordinates before
assigning them to the properties to cause the
move */
[Link] = x + "px";
[Link] = y + "px";
/* Recursive call, after a 1-millisecond delay */
setTimeout("moveText(" + x + "," + y + ")", 1);
}
} /*** end of function moveText */
Drag-and-drop allows users to move elements around the screen. Drag-and-drop can be done entirely with
DOM 0. But to make it work in all browsers, you’d need browser detection and different code for each.
DOM 2 is preferred for cleaner, portable code. DOM 0 model: Simple but less portable. Example: inline
onmousedown="grabber(event)". DOM 2 model: More modern and portable (addEventListener and
removeEventListener). The example uses DOM 2 for most handlers to avoid browser-specific code
differences.
Achieved by:
Listening to mousedown, mousemove, and mouseup events.
Changing the element’s top and left properties to update its position.
Uses stored differences to update element’s top and left as the mouse moves.
[Link]
<!DOCTYPE html>
<!-- [Link]
An example to illustrate the DOM 2 Event model
Allows the user to drag and drop words to complete
a short poem.
Does not work with IE browsers before IE9
-->
<html lang = "en">
<head>
<title> Drag and drop </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "[Link]" >
</script>
</head>
<body style = "font-size: 20;">
<p>
Roses are red <br />
Violets are blue <br />
<span style = "position: absolute; top: 200px; left: 0px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> candy </span>
<span style = "position: absolute; top: 200px; left: 75px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> cats </span>
<span style = "position: absolute; top: 200px; left: 150px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> cows </span>
<span style = "position: absolute; top: 200px; left: 225px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> glue </span>
<span style = "position: absolute; top: 200px; left: 300px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> is </span>
<span style = "position: absolute; top: 200px; left: 375px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> is </span>
<span style = "position: absolute; top: 200px; left: 450px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> meow </span>
<span style = "position: absolute; top: 250px; left: 0px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> mine </span>
<span style = "position: absolute; top: 250px; left: 75px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> moo </span>
<span style = "position: absolute; top: 250px; left: 150px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> new </span>
<span style = "position: absolute; top: 250px; left: 225px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> old </span>
<span style = "position: absolute; top: 250px; left: 300px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> say </span>
<span style = "position: absolute; top: 250px; left: 375px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> say </span>
<span style = "position: absolute; top: 250px; left: 450px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> so </span>
<span style = "position: absolute; top: 300px; left: 0px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> sticky </span>
<span style = "position: absolute; top: 300px; left: 75px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> sweet </span>
<span style = "position: absolute; top: 300px; left: 150px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> syrup </span>
<span style = "position: absolute; top: 300px; left: 225px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> too </span>
<span style = "position: absolute; top: 300px; left: 300px;
background-color: lightgrey;"
onmousedown = "grabber(event);"> yours </span>
</p>
</body>
</html>
[Link]
// [Link]
// An example to illustrate the DOM 2 Event model
// Allows the user to drag and drop words to complete
// a short poem.
// Does not work with IE browsers before IE9
// Define variables for the values computed by
// the grabber event handler but needed by mover
// event handler
var diffX, diffY, theElement;
// *******************************************************
// The event handler function for grabbing the word
function grabber(event) {
Display of [Link]
Chapter 2
Welcome to React
Understanding React components changes how you think about and approach web development.
Components promote a modular, reusable, and structured coding style. Learning components is like
opening a door to a new development perspective. Encourages breaking UI into smaller pieces that
manage their own logic and rendering. Some obstacles exist before you can write production-ready React
code.
React Is a Library
ReactJS is an open-source frontend JavaScript library that is used for building beautiful and dynamic
webpages, especially for single-page applications. It was made by and is now taken care of by Facebook.
Its main focus is on building user interfaces (UI), it also handles how the UI changes over time.
Currently, react is one of the most popular libraries for frontend development because of its component-
based architecture, easier understanding, and flexibility.
React is categorized as a library because it provides a collection of tools, including components and
functions, for use, without enforcing strict rules or structures for building the entire application. The
core concept of React revolves around creating reusable UI components, which can be managed,
updated, and reused. React offers greater flexibility, concentrating specifically on aspects of the user
interface. It focuses primarily on the view layer of the application, managing UI rendering and
manipulation.
React matured during a transformative period in JavaScript’s history. This period was chaotic because of
big changes in how JavaScript evolved.
Examples:
Older JS version
1:
2:
3:
if (![Link]) {
[Link] = "SNPSU";
}
1:
2:
const message = `Hello ${name}! Today is ${day}`;
3:
[Link] || = "SNPSU";
JavaScript is not purely functional, but functional concepts can be applied in its code. More and more
developers are using functional programming ideas in JavaScript. React emphasizes functional
programming over object-oriented programming.
Example:
function App() {
return (
<div>
<Welcome name="SNPSU" />
</div>
);
}
export default App;
Immutability
Example:
Composition
Example:
//Component 1
function Header() {
return <h1>Welcome!</h1>;
}
//Component 2
function Footer() {
return <p>© 2025 My App</p>;
}
Better testability (functions are easier to test than classes with internal state). Potential performance
improvements due to predictable behaviour.
React’s Future
React is still relatively new. Core functionality is fairly stable, but changes can still occur because of
reimplementation of React’s core algorithm. Main goal is to increase rendering speed for updates and UI
changes. Exact impact on developers is not yet fully known & many React changes are driven by the
range of devices being targeted.
React and related tools sometimes introduce breaking changes. Future updates may cause some example
code to stop working. Code samples will still work if you use the exact package versions specified in
[Link] & Install dependencies based on those version numbers.
Official React blogs posts detailed announcements for new versions including changelogs explaining
updates and changes. If you can’t attend conferences in person, Talks are often released on YouTube after
the events. There are also a variety of popular React conferences that you can attend for the latest React
information. These include:
React Conf
Facebook-sponsored conference in the Bay Area
React Rally
Community conference in Salt Lake City
ReactiveConf
Community conference in Bratislava, Slovakia
React Amsterdam
Community conference in Amsterdam
File Repository:
Main benefit:
o Click a link → instantly start editing and experimenting with the code.
When you edit or create a JSBin - Generates a unique URL for your code.
JSBin URL structure:
Installing [Link]:
When working with Node and React, you will need to use the command line. On the Mac, this is called
the Terminal. On a PC, it is called the Command Prompt. Run the following commands to check your
current version on node and npm (Node Package Manager)
First, check to see if you have [Link] installed: Open windows power shell & give the following
command
node –v
npm -v
If the command is not found, you'll need to install [Link] from the [Link] website
([Link] Download the installer, run it, and follow the instructions.
Command to create a react app after installing [Link]: (give this command in the terminal)