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

Web Programming

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

Web Programming

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

WEB PROGRAMMING

UNIT - I SCRIPTING
 HTML is known as HyperText Markup Language. It is a combination of both Hypertext
and Markup language.
 hypertext means the link between the web pages and markup is used to define the text
document within tag which defines the structure of web pages.
 It acts as a skeleton of a web page and without HTML it would be very difficult or
impossible to build a webpage.
 It is used by all the browsers and used to manipulate text, images, and other content, in
order to display it in the required format.
Creating an HTML document
The first step of creating a web page is to create an HTML document. An HTML document can
be created in any text editor even on a notepad. So any text editor can be used to make an Html
file. We just need to add extension .html /.htm
To create an HTML document follow the following steps:
1. Open your text editor such as Notepad
2. Write the code given below in the text editor.
<!DOCTYPE html>
<html>
<head>
<title>First HTML file</title>
</head>
<body>
Hello Everyone!!
</body>
</html>
3. Save this file with the .html/.htm extension.
4. Open that file with any browser. The output will be displayed.
Scripting basics:

 The process of creating and embedding scripts in a web page is known as web-
scripting.
 A script or a computer-script is a list of commands that are embedded in a web-page
normally and are interpreted and executed by a certain program or scripting engine.
 Scripts may be written for a variety of purposes such as for automating processes on
a local-computer or to generate web pages.
 The programming languages in which scripts are written are called scripting
language, there are many scripting languages available today.
 Common scripting languages are VBScript, JavaScript, ASP, PHP, PERL, JSP etc.
Types of Script :
Scripts are broadly of following two type :

Client-Side Scripts :
1. Client-side scripting is responsible for interaction within a web page. The client-
side scripts are firstly downloaded at the client-end and then interpreted and
executed by the browser (default browser of the system).
2. The client-side scripting is browser-dependent. i.e., the client-side browser must be
scripting enables in order to run scripts
3. Client-side scripting is used when the client-side interaction is used. Some example
uses of client-side scripting may be :
 To get the data from user’s screen or browser.
 For playing online games.
 Customizing the display of page in browser without reloading or
reopening the page.
4. Here are some popular client-side scripting languages VBScript, JavaScript,
Hypertext Processor(PHP).

Server-Side Scripts :
1. Server-side scripting is responsible for the completion or carrying out a task at the
server-end and then sending the result to the client-end.
2. In server-side script, it doesn’t matter which browser is being used at client-end,
because the server does all the work.
3. Server-side scripting is mainly used when the information is sent to a server and to
be processed at the server-end. Some sample uses of server-scripting can be :
 Password Protection.
 Browser Customization (sending information as per the requirements of
client-end browser)
 Form Processing
 Building/Creating and displaying pages created from a database.
 Dynamically editing changing or adding content to a web-page.
4. Here are some popular server-side scripting languages PHP, Perl, ASP (Active
Server Pages), JSP ( Java Server Pages).

Java Script-Object

In JavaScript, objects are a fundamental data type that allows you to group related data and
functionality together

Objects are instances of the Object class and are created using either object literals or the
Object constructor.

Object Literals:
Object literals are a concise way to create objects directly in your code. They consist of key-
value pairs enclosed in curly braces {}.

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

Object Properties
The name:values pairs in JavaScript objects are called properties:

Property Property Value

firstName John

lastName Doe
age 50

eyeColor blue

Accessing Object Properties


access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
JavaScript objects are containers for named values called properties.
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

A method is a function stored as a property.

Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this refers to the person object:
this.firstName means the firstName property of person.
this.lastName means the lastName property of person.

What is this?
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

Java Script-literals
JavaScript Literals are the fixed value that cannot be changed, you do not need to specify any
type of keyword to write literals.
Literals are often used to initialize variables in programming, names of variables are string
literals.
A JavaScript Literal can be a numeric, string, floating-point value, a boolean value or even an
object.
JavaScript supports various types of literals which are listed below:
 Numeric Literal
 Floating-Point Literal
 Boolean Literal
 String Literal
 Array Literal
 Regular Expression Literal
 Object Literal
Numeric Literals: Numeric literals represent numbers. They can be integers or floating-point
numbers.
let integerLiteral = 42;
let floatLiteral = 3.14;

String Literals: String literals represent textual data and are enclosed in single or double quotes.

let singleQuotedString = 'Hello, world!';


let doubleQuotedString = "JavaScript is awesome!";

Boolean Literals: Boolean literals represent the two boolean values, true or false.
let trueLiteral = true;
let falseLiteral = false;
Array Literals: Array literals represent ordered collections of values and are enclosed in square
brackets.
let numbers = [1, 2, 3, 4, 5];
let colors = ['red', 'green', 'blue'];
Object Literals: Object literals represent key-value pairs and are enclosed in curly braces.
let person = {
name: 'John',
age: 30,
isStudent: false
};

RegExp (Regular Expression) Literals: RegExp literals represent patterns for matching
character combinations in strings.
let regexLiteral = /\d+/; // Matches one or more digits
Null Literal: The null literal represents the absence of any object value.
let nullValue = null;
Undefined Literal: The undefined literal represents an uninitialized variable or missing
property.
let undefinedValue = undefined;

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:

var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.

Operator Description Example


+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison operators are
as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false


<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true


JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators

The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-
else.

, Comma Operator allows multiple expressions to be evaluated as single


statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type


new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

JavaScript Statements
Example
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

A computer program is a list of "instructions" to be "executed" by a computer.


In a programming language, these programming instructions are called statements.
A JavaScript program is a list of programming statements.
javaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";

JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
Examples
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
JavaScript White Space
JavaScript ignores multiple spaces.

The following lines are equivalent:

let person = "Hege";


let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;

JavaScript Line Length and Line Breaks


For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.

Keyword Description

var Declares a variable

let Declares a block variable


const Declares a block constant

if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of statements

JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the execution.
This process of reacting over the events is called Event Handling. Thus, js handles the HTML
events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
Some of the HTML events and their event handlers are:
Mouse events:

Event Event Description


Performed Handler

click onclick When mouse click on an element


mouseover onmouseover When the cursor of the mouse comes over the
element

mouseout onmouseout When the cursor of the mouse leaves an


element

mousedown onmousedown When the mouse button is pressed over the


element

mouseup onmouseup When the mouse button is released over the


element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Event Handler Description


Performed

Keydown & onkeydown & When the user press and then release the
Keyup onkeyup key

Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form


blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a


form element

Window/Document events

Event Event Description


Performed Handler

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the
browser unloads it

resize onresize When the visitor resizes the window of the


browser

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>JavaScript Events</title>

</head>
<body>

<button id="myButton">Click me</button>

<script>

// Get a reference to the button element

var myButton = document.getElementById('myButton');

// Attach an event listener to the button

myButton.addEventListener('click', function() {

alert('Button clicked!');

});
</script>
In JavaScript, the window object is a global object that represents the browser window
Here are some common properties and methods associated with the window object:
1. Properties:
 window.innerWidth and window.innerHeight: Returns the inner width and
height of the browser window's content area.
 window.outerWidth and window.outerHeight: Returns the outer width and
height of the browser window, including toolbars and other browser chrome.
2. Methods:
 window.alert(): Displays a dialog box with a specified message and an OK button.
 window.confirm(): Displays a dialog box with a specified message, an OK button,
and a Cancel button.
 window.prompt(): Displays a dialog box that prompts the user for input.
 window.open(): Opens a new browser window or a new tab, depending on the
browser's settings.
 window.close(): Closes the current browser window.
3. Navigation:
 window.location: Represents the current URL of the browser.
 window.location.href: Gets or sets the complete URL.
 window.location.reload(): Reloads the current page.

4. Timers:
 window.setTimeout(): Calls a function or evaluates an expression after a specified
number of milliseconds.
 window.setInterval(): Calls a function or evaluates an expression at specified
intervals.

5. Document Object Model (DOM):


 window.document: Represents the DOM document object for the current page.
It's important to note that many properties and methods of the window object can be
accessed directly without using the window prefix. For example, you can use alert()
instead of window.alert().

Program

<!DOCTYPE html>
<html lang="en">
<head>
<title>Open New Window</title>
</head>
<body>

<button onclick="openNewWindow()">Open New Window</button>

<script>
function openNewWindow() {
// Specify the URL and window features
var url = "https://www.google.com";
var windowFeatures = "width=600,height=400";

// Open a new window


var newWindow = window.open(url, "_blank", windowFeatures);

// Check if the window was successfully opened


if (newWindow) {
// Focus on the new window
newWindow.focus();
} else {
// Alert the user if the window couldn't be opened
alert("Unable to open a new window. Please check your browser settings.");
}
}
</script>

</body>
</html>

Frames in JavaScript typically refer to the concept of using HTML framesets to divide
a web page into multiple frames, each containing a separate HTML document. However,
it's essential to note that the use of framesets has become outdated, and the modern
approach is to use alternative techniques such as iframes or to design single-page
applications using JavaScript frameworks.
1. HTML Framesets:
In the traditional approach, you could use HTML framesets to create a page with multiple
frames. Framesets have been deprecated in HTML5, and their use is generally
discouraged due to various usability and accessibility issues. However, for historical
context, here's a simple example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frameset Example</title>
</head>
<frameset cols="50%,50%">
<frame src="frame1.html" name="frame1">
<frame src="frame2.html" name="frame2">
</frameset>
</html>

Using iframes:
Instead of framesets, you can use inline frames (<iframe>) to embed documents within a
page. iframes are more flexible and offer better control over content isolation.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iframe Example</title>
</head>
<body>

<iframe src="frame1.html" width="50%" height="300px" title="Frame 1"></iframe>


<iframe src="frame2.html" width="50%" height="300px" title="Frame 2"></iframe>

</body>
</html>

3. JavaScript and Frames:

If you need to interact with frames using JavaScript, you can access frames using the
window.frames object. Each frame is accessible by its index or name attribute.

// Accessing a frame by index


var frame = window.frames[0];

// Accessing a frame by name


var frame = window.frames["frame1"];

// Accessing a document inside a frame


var frameDocument = frame.document;
Remember, manipulating frames directly using JavaScript might lead to security issues,
and it's often better to design your application using modern techniques like AJAX,
single-page applications (SPAs), or other frameworks/libraries for a more seamless user
experience.

JavaScript has a variety of built-in functions that provide useful functionality for tasks
like working with strings, numbers, arrays, and more. Here's a list of some commonly
used built-in functions in JavaScript:

1. String Functions:
String.length: Returns the length of a string.

var message = "Hello, World!";


console.log(message.length); // Outputs 13

2. String.toLowerCase() and String.toUpperCase(): Convert a string to lowercase or


uppercase.

var text = "Hello";


console.log(text.toLowerCase()); // Outputs "hello"
console.log(text.toUpperCase()); // Outputs "HELLO"

3. String.indexOf(substring): Returns the index of the first occurrence of a substring.

var sentence = "This is a sample sentence.";


console.log(sentence.indexOf("sample")); // Outputs 10

4. Number Functions:
Number.toFixed(decimals): Formats a number using fixed-point notation with a
specified number of decimals.

var pi = 3.14159;
console.log(pi.toFixed(2)); // Outputs "3.14"

parseInt(string, radix): Parses a string and returns an integer.

var numberString = "42";


console.log(parseInt(numberString)); // Outputs 42

Array Functions:

Array.length: Returns the length of an array.


var numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Outputs 5

Array.push(element): Adds an element to the end of an array.

var fruits = ["apple", "banana"];


fruits.push("orange");
console.log(fruits); // Outputs ["apple", "banana", "orange"]

Array.pop(): Removes the last element from an array.

var colors = ["red", "green", "blue"];


colors.pop();
console.log(colors); // Outputs ["red", "green"]

Array.join(separator): Joins all elements of an array into a string.

var words = ["Hello", "World"];


console.log(words.join(" ")); // Outputs "Hello World"

4. Math Functions:
 Math.random(): Returns a random floating-point number between 0 (inclusive) and 1
(exclusive).

var randomNumber = Math.random();


console.log(randomNumber);

Math.floor(value), Math.ceil(value), and Math.round(value): Round a number down,


up, or to the nearest integer.

var decimalNumber = 5.67;


console.log(Math.floor(decimalNumber)); // Outputs 5
console.log(Math.ceil(decimalNumber)); // Outputs 6
console.log(Math.round(decimalNumber)); // Outputs 6

Browser Object Model


1. Browser Object Model (BOM)

The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of window by
specifying window or directly. For example:
1. window.alert("hello javatpoint");

is same as:

1. alert("hello javatpoint");
he document object represents an html document. It forms DOM (Document Object Model).

Window Object
The window object represents a window in browser. An object of window is created
automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript objects are
string, array, date etc

Methods of window object

The important methods of window object are as follows:

Method Description

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel
button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.


close() closes the current window.

setTimeout() performs action after specified time like calling function, evaluating
expressions etc.

Example of alert() in javascript

It displays alert dialog box. It has message and ok button.

1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

JavaScript History Object


The JavaScript history object represents an array of URLs visited by the user. By using this
object, you can load previous, forward or any particular page.

The history object is the window property, so it can be accessed by:

1. window.history

Or,

1. history

Property of JavaScript history object

There are only 1 property of history object.

No. Property Description

1 length returns the length of the history URLs.


Methods of JavaScript history object

There are only 3 methods of history object.

No. Method Description

1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

Example of history object

Let’s see the different usage of history object.

1. history.back();//for previous page


2. history.forward();//for next page
3. history.go(2);//for next 2nd page
4. history.go(-2);//for previous 2nd page
JavaScript Navigator Object

The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by:

1. window.navigator

Or,

1. navigator

JavaScript Screen Object


The JavaScript screen object holds information of browser screen. It can be used to display
screen width, height, colorDepth, pixelDepth etc.
The navigator object is the window property, so it can be accessed by:
1. window.screen Or,

1. screen

Property of JavaScript Screen Object

There are many properties of screen object that returns information of the browser.

No. Property Description

1 width returns the width of the screen

2 height returns the height of the screen

3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth

6 pixelDepth returns the pixel depth.

Example of JavaScript Screen Object


Let’s see the different usage of screen object.

<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
</script>

output
screen.width: 1366
screen.height: 768

Document Object Model


The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.

Properties of document object


Let's see the properties of document object that can be accessed and
modified by the document
object.
Methods of document object
We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with


newline character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name


value.

getElementsByTagNam returns all the elements having the given tag


e() name.

getElementsByClassNa returns all the elements having the given class


me() name.

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we
are using document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with
welcome message.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10.<input type="button" onclick="printvalue()" value="print name"/>
11. </form>

JavaScript Form Validation


It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name
can’t be empty and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be
forwarded to the next page until given values are correct.

<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return vali
dateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

You might also like