Web Programming
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:
firstName John
lastName Doe
age 50
eyeColor blue
firstName John
lastName Doe
age 50
eyeColor blue
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:
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.
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;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.
- Subtraction 20-10 = 10
/ Division 20/10 = 2
The JavaScript comparison operator compares the two operands. The comparison operators are
as follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
JavaScript Statements
Example
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
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.
let x = y + z;
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Keyword Description
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:
Keyboard events:
Keydown & onkeydown & When the user press and then release the
Keyup onkeyup key
Form events:
Window/Document events
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Events</title>
</head>
<body>
<script>
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.
Program
<!DOCTYPE html>
<html lang="en">
<head>
<title>Open New Window</title>
</head>
<body>
<script>
function openNewWindow() {
// Specify the URL and window features
var url = "https://www.google.com";
var windowFeatures = "width=600,height=400";
</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>
</body>
</html>
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.
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.
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"
Array Functions:
4. Math Functions:
Math.random(): Returns a random floating-point number between 0 (inclusive) and 1
(exclusive).
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
Method Description
confirm() displays the confirm dialog box containing message with ok and cancel
button.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
1. window.history
Or,
1. history
The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.
1. window.navigator
Or,
1. navigator
1. screen
There are many properties of screen object that returns information of the browser.
<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
</script>
output
screen.width: 1366
screen.height: 768
Method Description
Here, document is the root element that represents the html document.
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>
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>