Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views

Module 5-Advanced Scripting

Uploaded by

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

Module 5-Advanced Scripting

Uploaded by

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

WEB TECHNOLOGY AND ITS

APPLICATIONS
MODULE 5 –
Advanced Scripting
• JavaScript and Objects (SDL)
• Javascript own objects (SDL)
• The Document Object Model (DOM)
• Web browser Environments
• Forms and validation
Section 5 of 8

JAVASCRIPT OBJECTS
JavaScript Objects
Objects not Classes

❖JavaScript is not a full-fledged object-oriented programming


language.
❖It does not support many of the patterns you’d expect from an
object-oriented language like inheritance and polymorphism.
The language does, however, support objects.
JavaScript Objects
Not full-fledged O.O.

➢ Objects can have constructors, properties, and methods


associated with them.
➢ There are objects that are included in the JavaScript language;
you can also define your own kind of objects.
Constructors

➢ Normally to create a new object we use the new keyword, the


class name, and ( ) brackets with n optional parameters inside,
comma delimited as follows:
var someObject = new ObjectName(p1,p2,..., pn);
➢ For some classes, shortcut constructors are defined

var greeting = "Good Morning";

var greeting = new String("Good Morning");


Properties
Use the dot

➢ Each object might have properties that can be accessed,


depending on its definition.
➢ When a property exists, it can be accessed using dot notation
where a dot between the instance name and the property
references that property.
//show someObject.property to the user
alert(someObject.property);
Methods
Use the dot, with brackets

➢ Objects can also have methods, which are functions associated


with an instance of an object. These methods are called using
the same dot notation as for properties, but instead of accessing
a variable, we are calling a method.
someObject.doSomething();
➢ Methods may produce different output depending on the object
they are associated with because they can utilize the internal
properties of the object.
Objects Included in JavaScript
A number of useful objects are included with JavaScript
including:
• Array
• Boolean
• Date
• Math
• String
• Dom objects
Arrays

❑Arrays are one of the most used data structures. In practice, this
class is defined to behave more like a linked list in that it can be
resized dynamically, but the implementation is browser specific,
meaning the efficiency of insert and delete operations is
unknown.
❑The following code creates a new, empty array named greetings:

var greetings = new Array();


Arrays
Initialize with values

✓ To initialize the array with values, the variable declaration


would look like the following:
var greetings = new Array("Good Morning", "Good Afternoon");
or, using the square bracket notation:
var greetings = ["Good Morning", "Good Afternoon"];
Arrays
Access and Traverse

✓ To access an element in the array you use the familiar square


bracket notation from Java and C-style languages, with the
index you wish to access inside the brackets.
alert ( greetings[0] );
✓ One of the most common actions on an array is to traverse
through the items sequentially. Using the Array object’s length
property to determine the maximum valid index. We have:
for (var i = 0; i < greetings.length; i++){
alert(greetings[i]);
}
Arrays
Index and Value
Arrays
Modifying an array

✓ To add an item to an existing array, you can use the push


method.
greetings.push("Good Evening");
✓ The pop method can be used to remove an item from the back of
an array.
✓ Additional methods: concat(), slice(), join(), reverse(), shift(), and
sort()
Math

➢ The Math class allows one to access common mathematic


functions and common values quickly in one place.
➢ This static class contains methods such as max(), min(), pow(),
sqrt(), and exp(), and trigonometric functions such as sin(), cos(),
and arctan().
➢ Many mathematical constants are defined such as PI, E, SQRT2,
and some others
Math.PI; // 3.141592657
Math.sqrt(4); // square root of 4 is 2.
Math.random(); // random number between 0 and 1
String

❖The String class has already been used without us even knowing
it.
❖Constructor usage

var greet = new String("Good"); // long form constructor


var greet = "Good"; // shortcut constructor
❖Length of a string

alert (greet.length); // will display "4"


String
Concatenation and so much more

var str = greet.concat("Morning"); // Long form concatenation


var str = greet + "Morning"; // + operator concatenation
Many other useful methods exist within the String class, such as
• accessing a single character using charAt()
• searching for one using indexOf().
▪Strings allow splitting a string into an array, searching and
matching with split(), search(), and match() methods.
Date
Not that kind

❑The Date class is yet another helpful included object you should
be aware of.
❑It allows you to quickly calculate the current date or create date
objects for particular dates.
❑To display today’s date as a string, we would simply create a
new object and use the toString() method.
var d = new Date();
// This outputs Today is Mon Nov 12 2012 15:40:19 GMT-0700
alert ("Today is "+ d.toString());
Window

❖The window object in JavaScript corresponds to the browser itself.


Through it, you can access the current page’s URL, the browser’s
history, and what’s being displayed in the status bar, as well as
opening new browser windows.
❖In fact, the alert(), prompt(),confirm() function mentioned earlier is
actually a method of the window object.
Section 6 of 8

THE DOCUMENT OBJECT MODEL


(DOM)
The DOM
Document Object Model

oJavaScript is almost always used to interact with the HTML


document in which it is contained.
oThis is accomplished through a programming interface (API)
called the Document Object Model.

oAccording to the W3C, the DOM is a:


Platform- and language-neutral interface that will allow
programs and scripts to dynamically access and update the
content, structure and style of documents.
DOM Nodes
▪In the DOM, each element within the HTML document is
called a node. If the DOM is a tree, then each node is an
individual branch.
There are:
• element nodes,
• text nodes, and
• attribute nodes
▪All nodes in the DOM share a common set of properties and
methods.
DOM Nodes
Element, text and attribute nodes
DOM Nodes
Essential Node Object properties

Property Description

attributes Collection of node attributes

childNodes A NodeList of child nodes for this node


firstChild First child node of this node.
lastChild Last child of this node.
nextSibling Next sibling node for this node.
nodeName Name of the node
nodeType Type of the node
nodeValue Value of the node
parentNode Parent node for this node.
previousSiblin
g Previous sibling node for this node.
The DOM Programming
Interface
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and
methods of each object.
A property is a value that you can get or set (like
changing the content of an HTML element).
A method is an action you can do (like add or deleting
an HTML element).
<!DOCTYPE html>
<html>
<body>

<h2>My First Page</h2>

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

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
Document Object
One root to ground them all

❑The DOM document object is the root JavaScript object


representing the entire HTML document.
❑It contains some properties and methods that we will use
extensively in our development and is globally accessible as
document.
// specify the doctype, for example html
var a = document.doctype.name;
// specify the page encoding, for example ISO-8859-1
var b = document.inputEncoding;
Document Object
Document Object Methods

Method Description

createAttribute() Creates an attribute node

createElement() Creates an element node


createTextNode() Create a text node
Returns the element node whose id
getElementById(id) attribute matches the passed id
parameter.
getElementsByTagNa Returns a nodeList of elements
me(name) whose tag name matches the
passed name parameter.
Finding HTML Elements

Method Description

document.getElementById(id) Find an element by


element id
document.getElementsByTagName(name) Find elements by tag
name

document.getElementsByClassName(name) Find elements by


class name
Finding HTML Element by Id
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p id="intro">Finding HTML Elements by Id</p>
<p>This example demonstrates the <b>getElementsById</b> method.</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is: " + element.innerHTML;
</script>
</body>
</html>
Finding HTML Elements by
Class Name
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Class Name.</p>


<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b>
method.</p>

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

<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>

</body>
</html>
Changing HTML Elements
Property Description
element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML


element

element.style.property = new style Change the style of an HTML element

Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML
element
Changing HTML Content
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript can Change HTML</h2>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>
Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output


stream
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript DOM Manipulation</title>
</head>
<body>

<h2>JavaScript DOM Manipulation Example</h2>

<div id="container">
<p id="para1">This is the first paragraph.</p>
<p id="para2">This is the second paragraph.</p>
</div>

<script>
// 1. Create a new element
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph created using createElement.";
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript DOM Manipulation</title>
</head>
<body>

<h2>JavaScript DOM Manipulation Example</h2>

<div id="container">
<p id="para1">This is the first paragraph.</p>
<p id="para2">This is the second paragraph.</p>
</div>
<script>
// 2. Append the new element as the last child of the container
const container = document.getElementById("container");
container.appendChild(newParagraph);
</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript DOM Manipulation</title>
</head>
<body>

<h2>JavaScript DOM Manipulation Example</h2>

<div id="container">
<p id="para1">This is the first paragraph.</p>
<p id="para2">This is the second paragraph.</p>
</div>

<script>
// 3. Remove an existing child element
const para1 = document.getElementById("para1");
container.removeChild(para1);
</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript DOM Manipulation</title>
</head>
<body>
<h2>JavaScript DOM Manipulation Example</h2>
<div id="container">
<p id="para1">This is the first paragraph.</p>
<p id="para2">This is the second paragraph.</p>
</div>
<script>
// 4. Replace an existing child with a new child
const anotherParagraph = document.createElement("p");
anotherParagraph.textContent = "This paragraph will replace the second one.";
const para2 = document.getElementById("para2");
container.replaceChild(anotherParagraph, para2);
</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript DOM Manipulation</title>
</head>
<body>

<h2>JavaScript DOM Manipulation Example</h2>

<div id="container">
<p id="para1">This is the first paragraph.</p>
<p id="para2">This is the second paragraph.</p>
</div>

<script>
// 5. Use document.write to display additional text (not recommended for modern
use)
document.write("<p>This text is added using document.write.</p>");
</script>

</body>
</html>
Adding Events Handlers

Method Description
document.getElementById(id).onclick Adding event
= function(){code} handler code to
an onclick
event
Accessing nodes
getElementById(), getElementsByTagName()
Element node Object

The type of object returned by the method


document.getElementById() described in the previous section is an
element node object.
This represents an HTML element in the hierarchy, contained
between the opening <> and closing </> tags for this element.
• can itself contain more elements
Element node Object
Essential Element Node Properties

Property Description

className The current value for the class attribute of this


HTML element.

id The current value for the id of this element.


Represents all the things inside of the tags. This
innerHTML can be read or written to and is the primary way
which we update particular div's using JS.
style The style attribute of an element. We can read and
modify this property.
tagName The tag name for the element.
Modifying a DOM element

❖The document.write() method is used to create output to the


HTML page from JavaScript. The modern JavaScript programmer
will want to write to the HTML page, but in a particular location,
not always at the bottom
❖Using the DOM document and HTML DOM element objects, we
can do exactly that using the innerHTML property
Modifying a DOM element
More verbosely, and validated

➢ Although the innerHTML technique works well (and is very fast),


there is a more verbose technique available to us that builds
output using the DOM.
➢ DOM functions createTextNode(), removeChild(), and
appendChild() allow us to modify an element in a more rigorous
way
Changing an element’s style

✓ We can add or remove any style using the style or className


property of the Element node.
✓ Its usage is shown below to change a node’s background color and
add a three-pixel border.
var commentTag = document.getElementById("specificTag");
commentTag.style.backgroundColour = "#FFFF00";
commentTag.style.borderWidth="3px";
Changing an element’s style
With class

➢ The className property is normally a better choice, because it


allows the styles to be created outside the code, and thus be
better accessible to designers.
var commentTag = document.getElementById("specificTag");
commentTag.className = "someClassName";
➢ HTML5 introduces the classList element, which allows you to
add, remove, or toggle a CSS class on an element.
label.classList.addClass("someClassName");
More Properties
Some Specific HTML DOM Element Properties for Certain Tag Types

Property Description Tags


href The href attribute used in a tags to specify a a
URL to link to.
The name property is a bookmark to identify a, input,
name this tag. Unlike id which is available to all tags, textarea
name is limited to certain form related tags. , form

Links to an external URL that should be loaded img,


src into the page (as opposed to href which is a input,
iframe,
link to follow when clicked) script
The value is related tot he value attribute of
input tags. Often the value of an input field is Input,
value textarea
user defined, and we use value to get that , submit
user input.
Section 7 of 8

JAVASCRIPT EVENTS
JavaScript Events

•A JavaScript event is an action that can be detected by


JavaScript.
•We say then that an event is triggered and then it can be
caught by JavaScript functions, which then do something in
response.
JavaScript Events
A brave new world

❑In the original JavaScript world, events could be specified right in


the HTML markup with hooks to the JavaScript code (and still
can).
❑As more powerful frameworks were developed, and website
design and best practices were refined, this original mechanism
was supplanted by the listener approach.
JavaScript Events
Two approaches
Inline Event Handler Approach

❖For example, if you wanted an alert to pop-up when clicking a <div>


you might program:
<div id="example1" onclick="alert('hello')">Click for pop-up</div>
❖The problem with this type of programming is that the HTML markup
and the corresponding JavaScript logic are woven together. It does
not make use of layers;
❖that is, it does not separate content from behavior.
Listener Approach
Two ways to set up listeners
Add an Event Handler to an
Element
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to attach a click event to a


button.</p>
<button id="myBtn">Try it</button>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
</script>

</body>
</html>
Listener Approach
Using functions

❑What if we wanted to do something more elaborate when an


event is triggered? In such a case, the behavior would have to
be encapsulated within a function, as shown in Listing 6.12.
Listener Approach
Anonymous functions

An alternative to that shown in Listing 6.12 is to use


an anonymous function (that is, one without a
name), as shown in Listing 6.13.
Event Types

There are several classes of event, with several types


of event within each class specified by the W3C:
• mouse events
• keyboard events
• form events
• frame events
Mouse events

Event Description
onclick The mouse was clicked on an element
ondblclick The mouse was double clicked on an element
onmousedown The mouse was pressed down over an element
onmouseup The mouse was released over an element
onmouseover The mouse was moved (not clicked) over an
element
onmouseout The mouse was moved off of an element
onmousemove The mouse was moved while over an element
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onmousedown Event</h2>
<p>Clock the text below!</p>
<p id="myP" onmousedown="mouseDown()" onmouseup="mouseUp()">
The mouseDown() function sets the color of this text to red.
The mouseUp() function sets the color of this text to blue.
</p>
<script>
function mouseDown() {
document.getElementById("myP").style.color = "red";
}
function mouseUp() {
document.getElementById("myP").style.color = "blue";
}
</script>
</body>
</html>
Output
Keyboard events

Event Description
onkeydown The user is pressing a key (this
happens first)
onkeypress The user presses a key (this
happens after onkeydown)
onkeyup The user releases a key that was
down (this happens last)
Keyboard events
Example

❑<input type="text" id="keyExample">

❑The input box above, for example, could be listened to and


each key pressed echoed back to the user as an alert as shown
in Listing 6.15.
Form Events
Event Description
A form element has lost focus (that is, control has moved
onblur to a different element, perhaps due to a click or Tab key
press.
Some <input>, <textarea> or <select> field had their
onchange value change. This could mean the user typed something,
or selected a new choice.
Complementing the onblur event, this is triggered when
onfocus an element gets focus (the user clicks in the field or tabs to
it)
onreset HTML forms have the ability to be reset. This event is
triggered when that happens.
onselect When the users selects some text. This is often used to try
and prevent copy/paste.
When the form is submitted this event is triggered. We can
onsubmit do some pre-validation when the user submits the form in
JavaScript before sending the data on to the server.
Form Events
Example
Frame Events

❑Frame events are the events related to the browser frame that
contains your web page.
❑The most important event is the onload event, which tells us an
object is loaded and therefore ready to work with. If the code
attempts to set up a listener on this not-yet-loaded <div>, then
an error will be triggered.
window.onload= function(){
//all JavaScript initialization here.
}
Frame Events
Table of frame events

Event Description
onabort An object was stopped from loading

onerror An object or image did not properly load

onload When a document or object has been loaded

onresize The document view was resized

onscroll The document view was scrolled

onunload The document has unloaded


Section 8 of 8

FORMS
Validating Forms
You mean pre-validating right?

❑Writing code to prevalidate forms on the client side will


reduce the number of incorrect submissions, thereby
reducing server load.
❑There are a number of common validation activities
including email validation, number validation, and data
validation.
Validating Forms
Empty field
Validating Forms
Empty field

❖If you want to ensure a checkbox is ticked, use code like that
below.
var inputField=document.getElementByID("license");
if (inputField.type=="checkbox")
{
if (inputField.checked)
//Now we know the box is checked
}
Validating Forms
Number Validation
Submitting Forms

❖Submitting a form using JavaScript requires having a node


variable for the form element. Once the variable, say,
formExample is acquired, one can simply call the submit()
method:
var formExample = document.getElementById("loginForm");
formExample.submit();
✓ This is often done in conjunction with calling preventDefault()
on the onsubmit event.

You might also like