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

Unit IV Final

JavaScript is a scripting language used to add interactivity and functionality to web pages. It works in all major browsers and allows developers to dynamically modify HTML content, validate forms, detect browsers, and more. The Document Object Model (DOM) represents an HTML document as objects that can be manipulated with JavaScript. Key DOM objects include the window, document, form, and element objects which provide methods to access and modify the content, structure, and styling of a document. Common events that can trigger JavaScript functions include click, mouseover, and load.

Uploaded by

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

Unit IV Final

JavaScript is a scripting language used to add interactivity and functionality to web pages. It works in all major browsers and allows developers to dynamically modify HTML content, validate forms, detect browsers, and more. The Document Object Model (DOM) represents an HTML document as objects that can be manipulated with JavaScript. Key DOM objects include the window, document, form, and element objects which provide methods to access and modify the content, structure, and styling of a document. Common events that can trigger JavaScript functions include click, mouseover, and load.

Uploaded by

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

JAVASCRIPT

JavaScript is the scripting language of the Web.

JavaScript is used in millions of Web pages to add functionality, validate forms,


detect browsers, andmuch more.

Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design, validate


forms, detect browsers, createcookies, and much more.

JavaScript is the most popular scripting language on the Internet, and works in all
major browsers, such asInternet Explorer, Mozilla Firefox, and Opera.

What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
 Everyone can use JavaScript without purchasing a license

Java and JavaScript are two completely different languages in both concept and
design!

Java (developed by Sun Microsystems) is a powerful and much more complex


programming language - inthe same category as C and C++.

What can a JavaScript Do ?

 JavaScript gives HTML designers a programming tool - HTML


authors are normally not programmers, but JavaScript is a scripting
language with a very simple syntax! Almost anyone canput small
"snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A
JavaScript statement like this:document.write("<h1>" + name +
"</h1>") can write a variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute
when something happens,like when a page has finished loading or
when a user clicks on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can
read and change the contentof an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to
validate form data beforeit is submitted to a server. This saves the server
from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript
can be used to detect the visitor's browser, and - depending on the
browser - load another page specifically designed for thatbrowser
 JavaScript can be used to create cookies - A JavaScript can be
used to store and retrieveinformation on the visitor's computer.

DOM In Java Script

Why DOM is 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, a corresponding document is
created(DOM). DOM is basically the representation of the same HTML document
but in a different format with the use of objects. Javascript interprets DOM easily
i.e javascript can not understand the tags(<h1>H</h1>) in HTML document but can
understand object h1 in DOM. Now, Javascript can access each of the objects (h1, p,
etc) by using different functions.
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. One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a representation
of the same document, they will create the same structure model, with precisely the
same objects and relationships.
Why called an Object Model?
Documents are modeled using objects, and the model includes not only the structure
of a document but also the behavior of a document and the objects of which it is
composed like tag elements with attributes in HTML.
Properties of DOM: Let’s see the properties of the document object that can be
accessed and modified by the document object.
Representation of the DOM
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.
Form Object: It is represented by form tags.
Link Object: It is represented by link tags.
Anchor Object: It is represented by a href tags.
Form Control Elements:: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.
Methods to access elements of Document Object:
write(“string”): Writes the given string on the document.
getElementById(): returns the element having the given id value.
getElementsByName(): returns all the elements having the given name value.
getElementsByTagName(): returns all the elements having the given tag name.
getElementsByClassName(): returns all the elements having the given class name.
querySelector(): returns all the elements having the given selector
querySelectorAll() : returns all the elements having all the selectors.

Gets Selector Syntax Method

ID #demo getElementById()

Class .demo getElementsByClassName()

Name name getElementsByName()

Tag demo getElementsByTagName()

Selector (single) querySelector()

Selector (all) querySelectorAll()


It is helpful when studying the DOM to work with the examples on your own to
ensure that you are understanding and retaining the information you learn.
EXAMPLE:

<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Accessing Elements in the DOM</title>

<style>
html { font-family: sans-serif; color: #333; }
body { max-width: 500px; margin: 0 auto; padding: 0 15px; }
div, article { padding: 10px; margin: 5px; border: 1px solid #dedede; }
</style>
</head>
<body>

<h1>Accessing Elements in the DOM</h1>

<h2>ID (#demo)</h2>
<div id="demo">Access me by ID</div>

<h2>Class (.demo)</h2>
<div class="demo">Access me by class (1)</div>
<div class="demo">Access me by class (2)</div>

<h2>Tag (article)</h2>
<article>Access me by tag (1)</article>
<article>Access me by tag (2)</article>

<h2>Query Selector</h2>
<div id="demo-query">Access me by query</div>

<h2>Query Selector All</h2>


<div class="demo-query-all">Access me by query all (1)</div>
<div class="demo-query-all">Access me by query all (2)</div>
</body>
</html>

EXAMPLE
<html>

<body>

<p id="intro">A Computer Science portal for geeks.</p>


<p>This example illustrates the <b>getElementById</b> method.</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"GeeksforGeeks introduction is: " + element.innerHTML;
</script>
</body>

</html>
Output:

What is an Event?

Event Handlers

Event Handlers are JavaScript methods, i.e. functions of objects, that


allow us as JavaScriptprogrammers to control what happens when
events occur.

Directly or indirectly, an Event is always the result of something a user does. For
example, we've alreadyseen Event Handlers like onClick and onMouseOver
that respond to mouse actions. Another type of Event, an internal change-of-state
to the page (completion of loading or leaving the page). An onLoad Event can
be considered an indirect result of a user action.

Although we often refer to Events and Event Handlers interchangeably, it's


important to keep in mind thedistinction between them. An Event is merely
something that happens - something that it is initiated by an Event Handler
(onClick, onMouseOver, etc...).

The elements on a page which can trigger events are known as "targets" or
"target elements," and we can easily understand how a button which triggers a
Click event is a target element for this event. Typically, events are defined
through the use of Event Handlers, which are bits of script that tell the browser
what todo when a particular event occurs at a particular target. These Event
Handlers are commonly written as attributes of the target element's HTML tag.

The Event Handler for a Click event at a form field button element is quite simple to
understand:

<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"


onClick="event_handler_code">

The event_handler_code portion of this example is any valid JavaScript and it


will be executed when thespecified event is triggered at this target element.

There are "three different ways" that Event Handlers can be used to trigger Events
or Functions.

Method 1 (Link Events):(Locating Mouse Cursor)


Places an Event Handler as an attribute within an <A
HREF= > tag, like this:

<A HREF="foo.html"
onMouseOver="doSomething()"> ... </A>

The next line is

<A HREF="foo.html"
onMouseOver="alert('Hello!');">Mouse
over me!
</A>

Method 2 (Actions within FORMs): (Reacting to mouse

click)

The second technique we've seen for triggering a Function in response to a mouse
action is to place an
onClick Event Handler inside a button type form element, like this:

<FORM>
<INPUT TYPE="button" onClick="alert('Hello!');">
</FORM>
While any JavaScript statement, methods, or functions can appear inside the
quotation marks of an EventHandler, typically, the JavaScript script that makes
up the Event Handler is actually a call to a function defined in the header of the
document or a single JavaScript command. Essentially, though, anything that
appears inside a command block (inside curly braces {}) can appear between the
quotation marks.

Method 3 (Actions within FORMs): (Reacting to change

in text)

For instance, if you have a form with a text field and want to call the function
checkField() whenever thevalue of the text field changes, you can define your text
field as follows:

<INPUT TYPE="text" onChange="checkField(this)">

Nonetheless, the entire code for the function could appear in quotation marks rather
than a function call:

<INPUT TYPE="text" onChange="if (this.value <= 5) {


alert("Please enter a number greater than 5");
}">

Method 4 (BODY onLoad & onUnLoad):

The third technique is to us an Event Handler to ensure that all required objects are
defined involve the onLoad and onUnLoad. These Event Handlers are defined in
the <BODY> or <FRAMESET> tag of anHTML file and are invoked when the
document or frameset are fully loaded or unloaded. If you set a flag

within the onLoad Event Handler, other Event Handlers can test this flags to see
if they can safely run,with the knowledge that the document is fully loaded and
all objects are defined. For example:

<SCRIPT>
var loaded = false;
function doit()

{
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}

</SCRIPT>
<BODY onLoad="loaded = true;">
-- OR --
<BODY onLoad="window.loaded = true;">

<FORM>
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (window.loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded) doit();">
</FORM>

</BODY>

The onLoad Event Handler is executed when the document or frameset is fully
loaded, which means that all images have been downloaded and displayed, all
subframes have loaded, any Java Applets and Plugins(Navigator) have started
running, and so on. The onUnLoad Event Handler is executed just before the
page is unloaded, which occurs when the browser is about to move on to a new
page. Be aware that whenyou are working with multiple frames, there is no
guarantee of the order in which the onLoad Event Handler is invoked for the
various frames, except that the Event Handlers for the parent frame is invoked
after the Event Handlers of all its children frames -- This will be discussed in
detail in Week 8.

Setting the bgColor Property

The first example allows the user to change the color by clicking buttons,
while the second exampleallows you to change colors by using drop down
boxes.

Event
Handlers

EVENT DESCRI
PTION
onAbort the user cancels loading of an image
input focus is removed from a form element (when the user clicks outside the
onBlur
field) orfocus is removed from a window
onClick the user clicks on a link or form element
onChange the value of a form field is changed by the user
onError an error happens during loading of a document or image
onFocus input focus is given to a form element or a window
onLoad once a page is loaded, NOT while loading
onMouseOut the user moves the pointer off of a link or clickable area of an image map
onMouseOver the user moves the pointer over a hypertext link
onReset the user clears a form using the Reset button
onSelect the user selects a form element’s field
onSubmit a form is submitted (ie, when the users clicks on a submit button)
onUnload the user leaves a page

Note: Input focus refers to the act of clicking on or in a form element or field.
This can be done byclicking in a text field or by tabbing between text fields.

Which Event
Handlers
Can Be Used

OBJECT EVENT HANDLERS AVAILABLE


Button element onClick, onMouseOver
Checkbox onClick
Clickable ImageMap area onClick, onMouseOver, onMouseOut
Document onLoad, onUnload, onError
Form onSubmit, onReset
Framesets onBlur, onFocus
Hypertext link onClick, onMouseOver, onMouseOut
Image onLoad, onError, onAbort

Radio button onClick


Reset button onClick
Selection list onBlur, onChange, onFocus
Submit button onClick
TextArea element onBlur, onChange, onFocus, onSelect
Text element onBlur, onChange, onFocus, onSelect
Window onLoad, onUnload, onBlur, onFocus

DOM Style position Property


The position property sets or returns the type of positioning method used by the
element. It may be static, relative, absolute or fixed.
Syntax:
Return position syntax:
object.style.position

Set position syntax:


object.style.position = "static | absolute | fixed | relative |
sticky | initial | inherit"

Return Value: It returns a string which represents the position type of the element.
Properties:
absolute: It positions the element relative to the first positioned element.

Example:

<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
position: relative;
top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to change the position property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
<p>This DIV element is placed 20 pixels from the top of its original position.</p>

<script>
function myFunction() {
document.getElementById("myDIV").style.position = "absolute";
}
</script>
</body>
</html>

Output:

static: It is the default property. The appearance of elements in the document


remains static in accordance with the document flow.

Example:

<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
position: relative;
top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to change the position property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
<p>This DIV element is placed 20 pixels from the top of its original position.</p>

<script>
function myFunction() {
document.getElementById("myDIV").style.position = "static";
}
</script>
</body>
</html>

fixed: It positions the elements relative to the browser window.


Example:

<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
position: relative;
top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to change the position property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
<p>This DIV element is placed 20 pixels from the top of its original position.</p>

<script>
function myFunction() {
document.getElementById("myDIV").style.position = "fixed";
}
</script>

</body>
</html>
relative: It positions the elements relative to the normal position, so “right:40”
signifies an addition of 40 pixels to the element’s RIGHT position.
Example:

<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
position: relative;
top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to change the position property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
<p>This DIV element is placed 20 pixels from the top of its original position.</p>

<script>
function myFunction() {
document.getElementById("myDIV").style.position = "relative";
}
</script>

</body>
</html>
sticky: It positions the elements based on the scroll position of the user.The scrolling
operation is performed between relative and fixed property values. By default, the
scroll position is set at relative value.
Example:

<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
position: relative;
top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to change the position property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
<p>This DIV element is placed 20 pixels from the top of its original position.</p>

<script>
function myFunction() {
document.getElementById("myDIV").style.position = "sticky";
}
</script>

</body>
</html>

initial: It sets the position to it’s default value.


Example:
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
position: relative;
top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to change the position property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
<p>This DIV element is placed 20 pixels from the top of its original position.</p>

<script>
function myFunction() {
document.getElementById("myDIV").style.position = "initial";
}
</script>

</body>
</html>

inherit: It inherits the position values of the parent element.


Example:

<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
position: relative;
top: 20px;
}
</style>
</head>
<body>

<p>Click the "Try it" button to change the position property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
<p>This DIV element is placed 20 pixels from the top of its original position.</p>

<script>
function myFunction() {
document.getElementById("myDIV").style.position = "inherit";
}
</script>

</body>
</html>

Moving elements and Element visibility in DOM


Example
Hide the content of a <p> element:
document.getElementById("myP").style.visibility = "hidden";
Description
The visibility property sets or returns whether an element should be visible.
The visibility property allows the author to show or hide an element. It is similar to
the display property. However, the difference is that if you set display:none, it hides
the entire element, while visibility:hidden means that the contents of the element will
be invisible, but the element stays in its original position and size.
Syntax

Return the visibility property:


object.style.visibility

Set the visibility property:

object.style.visibility =
"visible|hidden|collapse|initial|inherit"

Property Values

Value Description

visible The element is visible. This is default

hidden The element is not visible, but still affects layout

collapse When used on a table row or cell, the element is not visible
(same as "hidden")

initial Sets this property to its default value.

inherit Inherits this property from its parent element.

Difference between the display property and the visibility property:


<!DOCTYPE html>
<html>
<body>

<p id="myP1">This is some text.</p>


<p id="myP2">This is some text.</p>

<input type="button" onclick="demoDisplay()" value="Hide text with display


property">
<input type="button" onclick="demoVisibility()" value="Hide text with visibility
property">

<script>
function demoDisplay() {
document.getElementById("myP1").style.display = "visible";
}

function demoVisibility() {
document.getElementById("myP2").style.visibility = "hidden";
}
</script>

</body>
</html>

OUTPUT:

This is some text.

This is some text.

Ajax Introduction:
What is Ajax?
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts
of data with the server behind the scenes. This means that it is possible to update parts
of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the
content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook
tabs.

How AJAX Works

Advantages and Disadvantages of Ajax


When talking about technology and its uses, we usually discuss the pros and cons of
everything. Of course, like many other techniques, Ajax itself comes with many
different advantages and disadvantages.
Let’s have a deeper look at these 2 sides of Ajax technology these days.
Advantages of AJAX
 Reduce server traffic and increase speed
 The first and foremost advantage of Ajax is its ability to improve the performance
and usability of web applications.
 To explain more detailedly, Ajax techniques allow applications to render without
data, which reduces the server traffic inside requests. That being said, web
developers can lower the time consumption on both side’s responses significantly.
 As a result, your web’s visitors will never have to see a white window and wait
for pages to refresh with Ajax implementation.
 Enable asynchronous calls
 Ajax benefits web developers in how its framework can be used for lazy loading.
Those who don’t know what Lazy Loading is are an optimization technique that’s
widely used for online content.
 In essence, Ajax allows its users to make asynchronous calls to the web server
without reloading the whole web page. As a web visitor, you don’t have to wait
for the entire page to load entirely in order to access the entire page content.
 The concept of lazy loading assists in loading only the required section and
delays the remaining, until it is needed by users. Thus, Ajax Lazy Loading not
only improves a web page load it also has a positive impact on user experience
and conversion rates.
 XMLHttpRequest
 XMLHttpRequest is a request type widely used for sending a request to Ajax
pages. You can also call it with a different name: Asynchronous HTTP request. It
plays a vital role in the implementation of Ajax techniques for web development.
 XMLHttpRequest transfers and manipulates the XML data to and from a web
service using HTTP. Its purpose is to establish an independent connection
between the webpage’s client-side and server.
 Reduce bandwidth usage
 One more advantage of Ajax comes from the bandwidth usage. This action is
effective in improving web performance and load speed as well.
 Ajax makes the best use of the server’s bandwidth by fetching particle contents
instead of transmitting the entire page’s content. This means that you can bring
data from the database and store it into the database to perform background
without reloading the page.
 Form Validation
 In contrast to traditional form submission, where client-side validations occur
after submission, the AJAX method enables precise and immediate form
validation. AJAX provides speed, which is also one of its significant benefits.
Disadvantages of Ajax
 We’ve just listed out all the areas where Ajax can show its great potential in
implementation. Let’s move on to some possible drawbacks you can meet when
using Ajax.
 Open-source. View source is allowed, and anyone can view the code source
written for Ajax, which makes it less secure compared to other technologies
 Search Engines cannot index Ajax pages can not be indexed by Google as well as
other search engines
 The usage of Ajax can cause difficulties for your web pages to debug as well as
make them prone to possible security issues in the future
 Most importantly, Ajax has a considerable dependency on JavaScript, so only
browsers that support Javascripts or XMLHttpRequest can use pages with Ajax
techniques
 Users will find it challenging to bookmark a specific state of the application due
to the dynamic web page
 From the users’ perspective, when you click the back button on the browser, you
may not return to the previous state of the page but the entire page. This happens
because the pages with successive Ajax requests are unable to register with the
browser’s history
Some of the most important applications of AJAX are as follows:
Updating a webpage without reloading the page.
Requesting data from the server after the page has been loaded.
Receiving data from the server after the page has been loaded.
Sending data to the server in the background without disturbing UI or other processes.
The alternatives to AJAX are:
 Fetch API.
 Axios.
 jQuery. ajax.
 SuperAgent.
 XMLHttpRequest.
 WebSockets.
 Server-Sent Events (SSE)
 GraphQL.

You might also like