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

AWDT module 2

js programs

Uploaded by

Aditya Chugh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

AWDT module 2

js programs

Uploaded by

Aditya Chugh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

HTML DOM (Document Object Model) is a hierarchical representation of

HTML documents. It defines the structure and properties of elements on a


webpage, enabling JavaScript to dynamically access, manipulate, and
update content, enhancing interactivity and functionality.
Note: It is called a Logical structure because DOM doesn’t specify any
relationship between objects.
What is DOM?
DOM, or Document Object Model, is a programming interface that
represents structured documents like HTML and XML as a tree of objects.
It defines how to access, manipulate, and modify document elements
using scripting languages like JavaScript.
Why is DOM Required?
HTML is used to structure the web pages and JavaScript is used to
add behavior to our web pages. When an HTML file is loaded into the
browser, the JavaScript can not understand the HTML document directly.
So it interprets and interacts with the Document Object Model (DOM), which
is created by the browser based on the HTML document.
Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The
term structure model is sometimes used to describe the tree-like
representation of a document.
Each branch of the tree ends in a node, and each node contains
objects Event listeners can be added to nodes and triggered on an
occurrence of a given event.

• Window Object: Window Object is object of the browser which is


always at top of the hierarchy. It is like an API that is used to set and
access all the properties and methods of the browser. It is
automatically created by the browser.
• Document object: When an HTML document is loaded into a window,
it becomes a document object. The ‘document’ object has various
properties that refer to other objects which allow access to and
modification of the content of the web page. If there is a need to
access any element in an HTML page, we always start with accessing
the ‘document’ object. Document object is property of window object.

Methods of Document Object


DOM provides various methods that allows users to interact with and
manipulate the document. Some commonly used DOM methods are:
Method Description

write(“string”) Writes the given string on the document.

Returns the element having the given id


getElementById()
value.

Returns all the elements having the given


getElementsByName()
name value.

Returns all the elements having the given tag


getElementsByTagName()
name.

Returns all the elements having the given


getElementsByClassName()
class name.
JavaScript Events
are actions or occurrences that happen in the browser. They can be
triggered by various user interactions or by the browser itself.
Common events include mouse clicks, keyboard presses, page loads, and
form submissions. Event handlers are JavaScript functions that respond to
these events, allowing developers to create interactive web applications.

Event Attribute Description

onclick Triggered when an element is clicked.

onmouseover Fired when the mouse pointer moves over an element.

onmouseout Occurs when the mouse pointer leaves an element.

onkeydown Fired when a key is pressed down.

onkeyup Fired when a key is released.

onchange Triggered when the value of an input element changes.

onload Occurs when a page has finished loading.

onsubmit Fired when a form is submitted.

onfocus Occurs when an element gets focus.

onblur Fired when an element loses focus.


JavaScript Events Examples
Example 1: Here, we will display a message in the alert box when the
button is clicked using onClick() event. This HTML document features a
button styled to appear in the middle of the page. When clicked, the
button triggers the `hiThere()` JavaScript function, which displays an alert
box with the message “Hi there!”.
html

<!doctype html>
<html>

<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>

<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>

</html>
Output:

Example 2: Here, we will change the color by pressing UP arrow


key using onkeyup() event. This code defines a JavaScript function
`changeBackground()` that changes the background color of an input box
when the up arrow key is pressed. RGB color values are incremented with
each key press, cycling through colors.
html
<!doctype html>
<html>
<head>
<script>
let a=0;
let b=0;
let c=0;
function changeBackground() {
let x=document.getElementById('bg');
x.style.backgroundColor='rgb('+a+', '+b+', '+c+')';
a+=100;
b+=a+50;
c+=b+70;
if(a>255) a=a-b;
if(b>255) b=a;
if(c>255) c=b;
}
</script>
</head>

<body>
<h4>The input box will change color when UP arrow key is
pressed</h4>
<input id="bg" onkeyup="changeBackground()" placeholder="write something"
style="color:#fff">
</body>

</html>
Output:

JavaScript Event Handlers


JavaScript event handlers are functions that are executed in response
to specific events occurring in the browser.
They can be attached to HTML elements using event attributes
like onclick, onmouseover, etc., or added dynamically using
the addEventListener() method in JavaScript.
Event Handling in JavaScript is a software routine that processes actions that
happen when a user interacts with the page, such as mouse movements and
keystrokes. Event handlers in javascript are when an event is received by an event
handler from an event producer and the processes that follow. Events are handled
similarly in a browser. When the browser notices a change, it notifies an event
handler (a function) that is listening to a specific event. The actions are then carried
out as defined by these functions.
What are Event Handlers in JavaScript?
When an event, consider pressing a keyboard key or clicking an element, occurs on a DOM
or an HTML element, we can call the specific functions based on these events. Now, how
does the HTML element know when to call the mentioned JavaScript code or JavaScript
function? This is taken care of by the event handlers. The properties of DOM or HTML
elements are called event handlers to control how an element should respond to a given event.
The concept and operation of event handlers are summarised in the figure below:

As shown in the above figure, when a user clicks a specific mouse button or types a specific
keyword into the browser, that action activates the corresponding event handler for that
HTML element. The browser then shows the end users the effects of the actions that were
carried out on the webpage by the JavaScript code that was executed by the event handler.

Event handlers can be assigned directly using the equal (=) operator because they are
attributes of HTML/DOM elements as well

For registering handlers, there are two recommended methods. By assigning the event
handler code to the target element's corresponding on event property or by adding the handler
as a listener for the element using the addEventListener() method, the event handler code can
be made to execute when an event is triggered. The handler will receive an object that
complies with the Event interface in either scenario (or a derived interface). The main
difference is that using the event listener methods, additional event handlers can be added (or
removed).

Different Phases of Event Handling in JavaScript


The lifecycle of a JavaScript event contains three different phases of events:

• Capturing Phase: In the capture phase, generally known as the trickling phase, the event
"trickles down" to the element that caused the event.
• Target Phase: It starts with the element and handler at the top level and works its way down
to the element. When the event arrives at the target, the capture phase is over.
• Bubbling Phase: The event is "bubbled" up to the DOM tree during the bubble phase. The
innermost handler initially captures and handles it (the one that is closest to the element on
which the event occurred). After that, it moves up (or bubbles up) to the DOM tree's higher
levels, moves up to its parents, and eventually returns to its root.

They follow the same order as listed above. As shown in the diagram below:

DOCUMENT

HTML

BODY

DIV

BUTTON

In event handling, when an event reaches the element, it enters the capturing phase. Events
enter the target phase when they reach the element, and they up from the element during
the bubbling phase.

Event Objects
Event handler functions accept an argument, the event object, even though we haven't used it
up to this point. Additional information about the event is also included in this object. For
example, we can check the event object's button property to verify which mouse button was
pressed.

<button> Click me! </button>


<script>
let btn = document.querySelector("button");
btn.addEventListener("mousedown", event => {
if (event.btn == 0) {
console.log("Left mouse button was pressed");
} else if (event.btn == 1) {
console.log("Middle mouse button was pressed");
} else if (event.btn == 2) {
console.log("Right mouse button was pressed");
}
});
</script>
Various Types of Event Handlers in JavaScript
JavaScript offers a variety of event handlers that are activated in response to specific actions
taken on the HTML elements. A few of the event handlers in javascript are:

Event
Description
Handler

When a click action occurs on an HTML element, this event handler runs a
JavaScript script. For example, the onClick event handler may be called when a
Onclick
button is clicked, a link is clicked, a checkbox is checked, or an image map is
selected.

When the mouse is over a particular link or object, this event handler runs a
onmouseover
JavaScript script.

When a window or image has fully loaded, this event handler executes some
Onload
JavaScript code.

onkeypress When a user presses a key, this event handler executes JavaScript code.

When the mouse leaves a specific link or object, this event handler runs a
onmouseout
JavaScript script.

When a key is released during a keyboard action, this event handler executes
Onkeyup
JavaScript code.

When a key is pressed on the keyboard during an action, this event handler runs
onkeydown
a JavaScript script.

Window Object Properties


The Window object in JavaScript has numerous properties that provide
access to various aspects of the browser environment and the window
itself. Here are some commonly used properties:
Property Name Description

Refers to the Document object


window.document representing the HTML document shown
in the window.

window.console Returns the window’s Console object.

The location attribute makes reference to


window.location the Location object, which has data about
the page’s current URL.
Property Name Description

window.defaultStatus It is now Abandoned.

If a window is closed, it returns a true


window.closed
boolean value.

window.frameElement It gives the window’s current frame back.

returns every window item currently active


window.frame
in the window.

window.history Retrieves the window’s History object.

It gives the number of iframe> elements


window.length
currently present in the window.

provides the ability to store key/value pairs


window.localStorage in a web browser. stores data without a
time.

Without including the toolbars and


window.innerWidth and
scrollbars, these characteristics describe
window.innerHeight
the width & height of the browser window.

It returns a pointer to the window that


window.opener
created the window in the opener function.

You can use outerHeight to return the


window.outerHeight height of the browser window, including
toolbars and scrollbars.

You can outerWidth to get the width of the


window.outerWidth browser window, including toolbars and
scrollbars.

window.name Returns or sets a window’s name.

Brings up the current window’s parent


window.parent
window.
Property Name Description

Provides the ability to store key/value pairs


window.sessionStorage in a web browser. Contains data for a
single session.

window.scrollX It is a pageXOffset alias.

Window Object Methods:


Methods in JavaScript are functions associated with objects. They
perform operations or calculate values. Here are some methods of the
Window object:

NOTE: Depending on the attributes, a parameter could have any value,


including a string, number, object, and more.
Here is a list of some of the methods of the window object:
Property Name Description

This method opens a new browser


window.open()
window or tab.

This method closes the current


window.close()
window or tab.

This method displays an alert


window.alert()
message to the user.

This method displays a prompt


window.prompt() message to the user and waits for
their input.

This method displays a confirm


message to the user and waits for
window.confirm()
their response.window.focus: brings
the current window or tab to the front.

Sends the current window or tab to


window.blur()
the back.
Property Name Description

Sends a message to the window or


window.postMessage() frame that is targeted by the specified
WindowProxy object.

Scrolls the window or frame to a


window.scrollTo()
specific position.

Scrolls the window or frame by a


window.scrollBy()
specific number of pixels.

window.resizeTo() Resizes the window to a specific size.

Resizes the window by a specific


window.resizeBy()
number of pixels.

A base-64 encoded string is decoded


window.atob()
via atob().

window.btoa() Base-64 encoding is done with btoa().

window.clearInterval() A timer set with setInterval() is reset.

The function clearTimeout() resets a


window.clearTimeout()
timer specified with setTimeout().

It switches the focus to the active


window.focus()
window.

This function returns the element’s


window.getComputedStyle()
current computed CSS styles.

It provides a Selection object


window.getSelection() corresponding to the user-selected
text selection range.

The provided CSS media query string


window.matchMedia()
is represented by a MediaQueryList
Property Name Description

object created by the matchMedia()


function.

Relocates a window with respect to its


window.moveBy()
present location.

Relocates a window to the given


window.moveTo()
location.

Displays what is currently displayed in


window.print()
the window.

Before the subsequent repaint, the


browser is asked to invoke a function
window.requestAnimationFrame()
to update an animation using the
requestAnimationFrame() method.

At predetermined intervals,
setInterval() calls a function or
window.setInterval()
evaluates an expression (in
milliseconds).

When a certain amount of


milliseconds have passed, the
window.setTimeout()
setTimeout() method calls a function
or evaluates an expression.

window.stop() It halts the loading of the window.

How to create frames ?



The task is to create frames using HTML. HTML
is HyperText Markup Language, and it is the standard markup language for
creating web pages. It describes the shape of a web page and includes a
sequence of elements.
Frames in HTML are used to divide your browser window into more than one
section in which every phase can load a separate HTML report and a group of
frames within the browser window is referred to as a frameset.
It is never recommended to use frames on your web page because of the
following reasons.
• Smaller gadgets can’t deal with frames frequently due to the fact that their
display isn’t always sufficient enough to be divided up.
• Due to different screen resolutions, your page will be displayed differently
on different computers.
• It happens sometimes that your browser’s back button doesn’t work as the
user hopes.
• There are few browsers that do not supports frame.
Let us see how we can create a frame using HTML.
Instead of using the <body> tag, you can use the <frameset> tag for using a
frame. The <frameset> tag is used to define how to divide the window into
frames. The horizontal frames are defined by the row attribute and the
vertical frames are defined by the col attribute.
Approach:
• First, create three separate files. eg – frame1.html, frame2.html, and
frame3.html.
• In the next step create the index.html file or main file to run the program
after including all the above HTML frames.
• All the below HTML files are used in both examples.

• frame1.html

<!DOCTYPE html>

<html>

<body>

<h3>frame 1</h3>

<p> This content is in frame 1 </p>

</body>

</html>

• frame2.html
<!DOCTYPE html>

<html>

<body>

<h3>frame 2</h3>

<p> This content is in frame 2 </p>

</body>

</html>

• frame3.html

<!DOCTYPE html>

<html>

<body>

<h3>frame 3</h3>

<p> This content is in frame 3</p>

</body>

</html>

Example 1: The following example demonstrates the HTML <frameset> with


cols attribute. The following code uses all of the above files i.e “frame1.html”,
“frame2.html” and “frame3.html” as frames.
• index.html

<!DOCTYPE html>
<html>

<body>

<frameset cols="*,*,*">

<frame src="frame1.html">

<frame src="frame2.html">

<frame src="frame3.html">

</frameset>

</body>

</html>

Output:

column frames

Example 2: In the following example, just change the cols to rows in


the <frameset> tag. The codes for “frame1.html”,”frame2.html”,”frame3.html”
are given before the examples.
• index.html
<!DOCTYPE html>

<html>

<body>

<frameset rows="*,*,*">

<frame src="frame1.html">

<frame src="frame2.html">

<frame src="frame3.html">

</frameset>

</body>

</html>

Output:
JavaScript Form Validation

JavaScript Form Validation is a way to ensure that the data users enter into a
form is correct before it gets submitted. This helps ensure that things like
emails, passwords, and other important details are entered properly, making
the user experience smoother and the data more accurate.
Steps for Form Validation in JavaScript
When we validate a form in JavaScript, we typically follow these steps:
• Data Retrieval:
o The first step is to get the user’s values entered into the form
fields (like name, email, password, etc.). This is done using
document.forms.RegForm, which refers to the form with the
name “RegForm”.
• Data Validation:
o Name Validation: We check to make sure the name field isn’t
empty and doesn’t contain any numbers.
o Address Validation: We check that the address field isn’t empty.
o Email Validation: We make sure that the email field isn’t empty
and that it includes the “@” symbol.
o Password Validation: We ensure that the password field isn’t
empty and that the password is at least 6 characters long.
o Course Selection Validation: We check that a course has been
selected from a dropdown list.
• Error Handling:
oIf any of the checks fail, an alert message is shown to the user
using window.alert, telling them what’s wrong.
o The form focuses on the field that needs attention, helping the
user easily fix the error.
• Submission Control:
o If all the validation checks pass, the function returns true,
meaning the form can be submitted. If not, it returns false,
stopping the form from being submitted.
• Focus Adjustment:
o The form automatically focuses on the first field that has an error,
guiding the user to fix it.

Types of Form Validation


• Client-side Validation:
o This is done in the user’s browser before the form is
submitted. It provides quick feedback to the user, helping
them fix errors without sending data to the server first.
• Server-side Validation:
o Even though client-side validation is useful, it’s important to
check the data again on the server. This ensures that the data
is correct, even if someone tries to bypass the validation in the
browser.
• An image rollover is basically two different images. One is displayed
after the page loaded up, the other one is displayed only when the user
moves his mouse over the first one. Image rollovers are often used for a
site’s interface. Currently this is the most popular JavaScript function.

• The following script listening shows you how create your own.

• Image Rollover Examples:

• <html>
• <head>
• <title>JavaScript Image Rollovers</title></head>
• <body>
• <a href="link.html"
• onMouseOver="document.image1.src='onImage.gif'"
• onMouseOut="document.image1.src='outImage.gif'">

• <img src="outImage.gif" name="image1">

• </a>
• </body>
• </html>
• This is the easiest rollover there
is. onMouseOver="document.image1.src='onImage.gif'" replaces “outImage.gif”
with
“onImage.gif”. onMouseOut="document.image1.src='outImage.gif'" swapps
“outImage.gif” back when the user moves his mouse away from it.

The position Property


The position property specifies the type of positioning method used for an
element.

There are five different position values:

• static
• relative
• fixed
• absolute
• sticky

Elements are then positioned using the top, bottom, left, and right
properties. However, these properties will not work unless
the position property is set first. They also work differently depending on the
position value.

position: static;
HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right
properties.

An element with position: static; is not positioned in any special way; it is


always positioned according to the normal flow of the page:

This <div> element has position: static;

Here is the CSS that is used:

Example
div.static {
position: static;
border: 3px solid #73AD21;
}

Try it Yourself »
position: relative;
An element with position: relative; is positioned relative to its normal
position.

Setting the top, right, bottom, and left properties of a relatively-positioned


element will cause it to be adjusted away from its normal position. Other
content will not be adjusted to fit into any gap left by the element.

This <div> element has position: relative;

Here is the CSS that is used:

Example
div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}

Try it Yourself »

ADVERTISEMENT

position: fixed;
An element with position: fixed; is positioned relative to the viewport, which
means it always stays in the same place even if the page is scrolled. The top,
right, bottom, and left properties are used to position the element.

A fixed element does not leave a gap in the page where it would normally
have been located.

Notice the fixed element in the lower-right corner of the page. Here is the
CSS that is used:
Example
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}

Try it Yourself »
This <div> element has position: fixed;

position: absolute;
An element with position: absolute; is positioned relative to the nearest
positioned ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it


uses the document body, and moves along with page scrolling.

Note: Absolute positioned elements are removed from the normal flow, and
can overlap elements.

Here is a simple example:

This <div> element has position: relative;

This <div> element has position: absolute;

Here is the CSS that is used:

Example
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}

div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}

Try it Yourself »

position: sticky;
An element with position: sticky; is positioned based on the user's scroll
position.

A sticky element toggles between relative and fixed, depending on the scroll
position. It is positioned relative until a given offset position is met in the
viewport - then it "sticks" in place (like position:fixed).

What is JavaScript Animation?


JavaScript animations are done by incremental programming changes in the style of an
element. JavaScript animations can perform tasks that CSS cannot. JavaScript could be
used to transfer several DOM elements across the page in accordance with a logical
equation or function. JavaScript includes the three functions mentioned below, which are
commonly used in animation programs.

1. setTimeout (function, duration): This function can be used to call the function after a
millisecond delay.
2. setInterval (function, duration): This function can be used to call the function after each
duration milliseconds.
3. clearTimeout (setTimeout_variable): This function can be used to clear the timer that
has been set by the setTimeout()

JavaScript can also modify a DOM object"s attributes, such as its location on the screen.
An object"s top and left attributes can be set to place it anywhere on the frame. The syntax
of JavaScript may be defined as:

A Navigation Bar is a user interface element commonly found in websites


and applications. It typically appears at the top of a web page or screen and
It’s an essential component of any website, allowing users to easily
navigate and access different sections or pages. In this tutorial, we will
make a responsive navigation bar using HTML, CSS, and JavaScript.
Approach
• Link the style.css and script.js files with the HTML code.
• First, we will add a header tag inside the body section and 3 more divs
for the logo, side nav menu, and hamburger menu.
• The logo will be on the left side and the navigation links will be on the
right side. The hamburger menu will only appear on a small display for
a better user experience.
• After that, we will style the Navbar and add an EventListener on
the Hamburger icon to only trigger when someone clicks on it.

You might also like