0% found this document useful (0 votes)
10 views8 pages

Unit 4

Uploaded by

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

Unit 4

Uploaded by

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

II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.

com
UNIT-IV
Q. What is an Object? How java script supports object orientation? Explain with example?
An object is a thing. It can be anything that we like from. Some data through a set of methods to an entire system.
The reason that object-Orientation is such a powerful idea is that quite simply it lets software designers and developers mimic
the real world in their designs. This idea might be so obvious as to be not worth mentioning after all software is usually
meant to solve real world problems. The benefit of OO is the tight linkage between the description of a problem and the ways
in which a can be solved.
Objects are described in software and design constructs called classes. A class usually contains some data items and
some methods. Each class provides service to other classes in the system. A single generic class can be specialized in many
ways and each of the specialized versions inherits. Some of the properties and behavior of the generic class. That means that
common parts of the program can be developed just once and easily reused.
An object is a runtime instance of a class. The object has all of the behavior that was defined in the class and is able
to perform processing. The dynamic aspects of an object are captured through pieces of code written inside methods. When
an object needs to do something, the appropriate method is executed.
JavaScript Objects: The built in JavaScript’s objects such as document and window act, and are used, like standard OO
object. JavaScript diverges from traditional OO is in its treatment of user-defined objects. An object is really a data structure
that has been associated with some functions. It doesn't have inheritance and the structure of the code can look a little
peculiar.
<html>
<head>
<script>
function ObjDemo() {
popup("Hello");
myhouse = new house("Dun Hacking", 2, 4);
alert(myhouse.name + " has " + myhouse.floors + " floors and " + myhouse.rooms() + " rooms");
myhouse.leave("Farewell");
}
function house(name, floors, beds){
this.name = name;
this.floors = floors;
this.bedrooms = beds;
this.rooms = frooms; // assign function reference
this.leave = popup; // assign function reference
}
function frooms(){
var groundfloor = 3;
var utilities = 2;
var total = 0;
if (this.floors <= 0){
total = 0;
}
else {
if (this.floors == 1){
total = this.bedrooms + utilities;
}
else {
total = this.floors * utilities;
total += groundfloor;
total += this.bedrooms;
}
}
return total;
}
function popup(msg){
alert(msg);
}
</script> </head>
<body onLoad="ObjDemo()">
</body></html>
The script is initiated as soon as the onload event happens during page loading. The demo() function performs four
tasks. First it calls the popup function which displays an alert box with the string Hello displayed. The next line of code does
something different and new.
myhouse = new house ("Dun Hacking", 2,4);
 new: Creates a new object by calling a constructor function
 this: Refers to the current object instance
 . (dot):Used to access an object's properties or methods
Q. What is Regular Expressions and explain the creation of regular expression?
A Regular Expression (RegExp) in JavaScript is a sequence of characters that forms a search pattern. It is used
for pattern matching within strings. JavaScript allows you to use regular expressions to search, match, replace, and split
strings.
Introduced after JavaScript version 1.1, regular expressions help in string manipulation and pattern matching.
Creation of Regular Expressions: There are two ways to create a regular expression in JavaScript:

Department of Computer Science, ADC-GDV Page-1


II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.com
1. Static Creation (Literal Notation)
var regex = /fish|fowl/;
 The pattern is hard-coded.
 More efficient when the pattern is known beforehand.
2. Dynamic Creation (Constructor Method)
var regex = new RegExp("fish|fowl");
 Used when the pattern is determined at runtime (e.g., user input).
 Slightly less efficient but more flexible.
JavaScript Regular Expression Grammar
RegExp Object Methods
Method Description
compile() Changes the regular expression pattern (rarely used now).
exec() Searches a string for a pattern. Returns the first match (with position).
test() Tests a string against a pattern. Returns true or false.
String Object Methods that Support RegExp
Method Description
search() Searches a string for a pattern. Returns index of the match or -1.
match() Searches and returns an array of all matched substrings.
replace( Replaces matched substrings with new values.
)
split() Splits the string into an array using the regular expression as the delimiter.
RegExp Modifiers (Flags)
Modifie Description
r
i Case-insensitive matching.
g Global match. Finds all matches, not just the first.
gi Global + case-insensitive match.
m Multiline matching. ^ and $ will match the start/end of each line (not just full string)
RegExp Modifiers - Literals
Modifie Description
r
\n Newline character
\f Form feed character
\r Carriage return character
\t Tab character
\v Vertical tab character
RegExp Modifiers - Character Classes
Modifier Description
[xyz] Match any one character in the set.
[^xyz] Match any character not in the set.
\w Match any alphanumeric character (letters, digits,
underscore).
\W Match any non-word character.
\d Match any digit (0-9).
\D Match any non-digit character.
\s Match any whitespace character (space, tab, etc.).
\S Match any non-whitespace character.
{x} Match exactly x occurrences.
? Match 0 or 1 occurrence.
* Match 0 or more occurrences.
+ Match 1 or more occurrences.
^ Match at the beginning of a string.
$ Match at the end of a string.
Example: Pattern Matching in JavaScript
<html>
<head><title>Pattern Matching</title></head>
<body>
<script language="javascript">
var msg = prompt("Enter the text", " ");
var hunt = prompt("Enter regular expression", " ");
var re = new RegExp(hunt);
var result = re.exec(msg);
document.write("<h1>Search Result</h1><p>");
if (result)
document.write("Found: " + result[0]);
else
document.write("Not Found");
document.write("</p>");
document.close();
</script>

Department of Computer Science, ADC-GDV Page-2


II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.com
</body>
</html>

Q. Explain Exception handling in java script with an example?


Runtime error handling is crucial in all programs. Programs should not simply fail or stop when a user enters
invalid data or when something unexpected happens. Many object-oriented programming languages provide a mechanism for
handling general classes of errors. This mechanism is called exceptional handling.
An exception in object-based programming is an object created dynamically at runtime, which encapsulates an error
and some information about it. You can define your own exception classes.
Keywords Used in Exception Handling:
throw
 An exception is an object created using the standard new method.

 Once the exception object exists, you need to do something with it, i.e., to throw the exception.

 Throwing the exception passes it back up the call stack until some code handles it.
Syntax: do something
if (an error happens) {
create a new exception object
throw the exception
}
try...catch
 The try...catch mechanism is used to try executing a block of statements that might cause an exception.

 If an exception is thrown by any statement inside the try block, execution of the whole block stops.

 The program then looks for a catch block to handle the exception.
Syntax: try {
statement one
statement two
statement three
} catch (exception) {
handle the exception
}
Example: <html>
<head> <title>Using Exceptions</title></head>
<body onLoad="RunTest()">
<script>
function InputException(msg) {
this.val = msg;
this.toString = function () {
return "Input Exception: Invalid input -> " + this.val;
};
}
function AreLetters(msg) {
var input = msg;
var re = /[^a-zA-Z]/; // matches anything NOT a letter
if (input.match(re)) {
let Oops = new InputException(input);
throw Oops;
}
}
function RunTest() {
var input = prompt("Type something (letters only):", "");
try {
AreLetters(input);
alert("Valid input: " + input);
} catch (e) {
alert(e.toString());
}
document.writeln("<h1>Using Exceptions</h1>");
document.writeln("<p>Check the prompt and alerts above.</p>");
document.close();
}
</script>
</body>
</html>
Q. JavaScript Built-in Objects
JavaScript provides several built-in objects to help you manipulate data, interact with web pages, and perform
common programming tasks. These objects are predefined by the language.

Department of Computer Science, ADC-GDV Page-3


II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.com
Document Object: The document object represents your HTML web page. It lets JavaScript interact with and change the
content of the page. You can add text, forms, change colors, or even create entire HTML content using JavaScript.
➤ Common Methods:
document.write() / document.writeln(): Used to write HTML content directly into the page during page load.
 document.write("<body>");
 document.write("<h1>A Test</h1>");
 document.write("<form>");

➤ Color Properties:
 bgColor: Sets the background color.
 fgColor: Sets the foreground (text) color.
 document.bgColor = "#e302334";
 document.fgColor = "coral";
➤ Arrays of HTML Elements:
 document.anchors[]: All named anchor (<a name="...">) elements.
 document.links[]: All links (<a href="...">) in the document.
 document.forms[]: All forms in the document.
 document.layers[]: Used in older browsers for positioned layers.
Window Object: The window object is the browser window itself. All JavaScript global functions and variables belong to
it. It lets you open new windows, control scrolling, change window size, and more.
➤ Important Methods:
 open(URL, name): Opens a new window with the specified URL.
 close(): Closes the current window.
 scroll(x, y): Scrolls the window by coordinates.
➤ Properties (used when opening a new window):
 toolbar=1|0
 location=1|0
 directories=1|0
 status=1|0
 menubar=1|0
 scrollbars=1|0
 resizable=1|0
 width=pixels, height=pixels
All can be set to 1 (on) or 0 (off).
Example: newWin = open("url", "newWin", "status=0,width=100,height=100,resizable=0");
Form Object: The form object helps you access input fields (like text boxes, radio buttons, etc.) in your HTML forms using
JavaScript.You can use it to check form data before it’s submitted, like checking if a name is entered.
➤ Example: <html>
<head> <title>Form Validation Example</title>
<script>
function validate(event) {
event.preventDefault(); // stop form from submitting
var value = document.forms[0].elements[0].value;
if (value !== "Mary") {
document.forms[0].reset();
alert("Invalid input. Try again!");
} else {
alert("Hi Mary!!");
}}
</script></head>
<body>
<form method="post" onsubmit="validate(event)">
<input type="text" name="user" size="32">
<input type="submit" value="Press Me!">
</form> </body> </html>
➤ Events:
 onClick="method": Triggered when an element is clicked.
 onSubmit="method": Triggered when the form is submitted.
 onReset="method": Triggered when the form is reset.
Browser Object (Navigator): The navigator object gives info about the user’s browser — like its name, version, and
plugins. You can check which browser the user has and make your code work better for them.
➤ Properties:
 navigator.appCodeName: Internal name (usually “Mozilla”).
 navigator.appName: Browser name.
 navigator.appVersion: Version and platform.
 navigator.userAgent: Full user agent string.
 navigator.plugins: Info about installed plugins.
 navigator.mimeTypes: Supported MIME types.
Use this object to detect browser capabilities and ensure compatibility.
Date Object: The Date object lets you work with dates and times in JavaScript.You can get the current time, show today’s
date, countdowns, or even calculate age.

Department of Computer Science, ADC-GDV Page-4


II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.com
JavaScript stores dates as the number of milliseconds since January 1, 1970 UTC (Unix Epoch Time).
➤ Constructors:
new Date(); // Current date and time
new Date(milliseconds); // From 01/01/1970
new Date("2025-09-10"); // From string
new Date(2025, 8, 10, 14, 30, 0); // (year, month, day, hour, min, sec)
➤ Parse: Date.parse("Mon, 9 April 2001 14:02:35 GMT");
Date Functions
Function Description
getDate() Returns day of the month
getDay() Returns day of the week (0 = Sunday)
getFullYear() Returns the year (4-digit)
getMonth() Month (0 = January)
getHours() Hour (0-23)
getMinutes() Minutes (0-59)
getSeconds() Seconds (0-59)
getMilliseconds() Milliseconds (0-999)
getTime() Milliseconds since 01/01/1970
setDate(day) Set day of month
setMonth(month) Set month (0 = Jan)
setFullYear(year, month?,
Set full year and optionally month/day
day?)
Set hours and optionally minutes,
setHours(h, m?, s?, ms?)
seconds
setMinutes(min, sec?, ms?) Set minutes
setSeconds(sec, ms?) Set seconds
setMilliseconds(ms) Set milliseconds
➤ Formatting Methods:
 toGMTString(): Returns date in GMT.
 toLocaleString(): Returns date in local format.
 toString(): Returns date as a string.
Q. JavaScript as an Event-Driven System
Event-driven programming is a paradigm where program flow depends on events like user actions or system
generated triggers. JavaScript reacts to events instead of running sequentially. Events can be clicks, keyboard inputs, form
submissions, page loading, etc.
JavaScript’s Event-Driven Nature
JavaScript waits for events from the browser or user interaction. It uses event listeners (handlers) to respond to these
events. This makes web pages interactive and responsive. The event loop manages event execution without blocking the
main thread.
Event Handler Description
blur onBlur The input focus moves away from the object, typically moving from a form field or form
itself.
change onChange The value of a form field is changed by the user (entering or deleting data).
click onClick The mouse is clicked on an element of the page.
dblclick onDblClick An element or link is clicked twice rapidly (double-click).
dragdrop onDragDrop A file or element is dragged and dropped onto the browser window.
focus onFocus Input focus is given to an element (opposite of blur).
keydown onKeyDown A key is pressed down but not yet released.
keypress onKeyPress A key is pressed (fires repeatedly while held down).
keyup onKeyUp A key is released.
load onLoad The page or resource is fully loaded by the browser.
mousedow onMouseDown A mouse button is pressed down.
n
mousemove onMouseMove The mouse pointer is moved.
mouseout onMouseOut The mouse pointer moves off an element.
mouseover onMouseOver The mouse pointer moves over an element.
mouseup onMouseUp A mouse button is released.
move onMove A window is moved, maximized, or restored by the user or script.
resize onResize A window is resized by the user or script.
select onSelect A form field or text is selected by mouse click or keyboard tabbing.
submit onSubmit A form is submitted (submit button clicked).
unload onUnload The user leaves the web page (page unload event).
<html>
<head> <title>Simple Event Example</title></head>
<body>
<input type="text" id="myInput" placeholder="Type here" />
<button id="myButton">Click me</button>
<p id="output"></p>
<script>
const input = document.getElementById('myInput');

Department of Computer Science, ADC-GDV Page-5


II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.com
const button = document.getElementById('myButton');
const output = document.getElementById('output');
input.addEventListener('change', () => {
output.textContent = 'Input changed to: ' + input.value;
});
button.addEventListener('click', () => {
alert('Button clicked!');
});
</script>
</body></html>
Q. What is the data validation? Explain?
Data validation is the process of ensuring that the data entered into a system or application is accurate, complete,
and formatted correctly before it is processed or stored. It's a key step in maintaining data integrity and preventing errors in
software applications, particularly those that accept user input (like forms on websites).
In web development, data validation can be performed in two main places:
1. Client-Side Validation
 This occurs in the user's browser, before the data is sent to the server.
 It helps users catch errors early (like entering text in a "phone number" field).
 It provides instant feedback without the delay of waiting for a server response.
 Example checks:
o Making sure a required field is not left blank.
o Ensuring that numbers are entered where expected.
o Checking that email addresses follow the proper format (e.g., user@example.com).
2. Server-Side Validation
 This happens on the server, after the data is submitted.
 It is more secure and robust.
 It should always be used in addition to client-side validation to ensure the data is safe and trustworthy.
 For example:
o Verifying that a user ID exists in the database.
o Checking that a password meets security standards.
o Ensuring uploaded files are the correct type and size.
Example: Email Validation
Validating email addresses is a common requirement:
 Emails follow a standard format (username@domain.com).
 A regular expression (regex) can be used to check the format.
 However, just checking format isn’t enough—you might still need to verify the email by sending a confirmation link.
Security Consideration
Client-side validation should not be used for sensitive checks like:
 Validating login credentials (e.g., matching user IDs and passwords),
 Restricting access based on role or permissions.
Validation an example
The following Web page has two text fields. One accepts names, the other accepts ages. Both fields are validated using
regular expressions and if the data is valid the contents of the form are transmitted in an email message.
<html>
<head>
<title>Data Validation</title>
</head>
<body>
<form method="post" action="#" onsubmit="return Validate()">
<table border="0">
<tr>
<th>Your Name</th>
<td><input type="text" size="24"></td>
</tr>
<tr>
<th>Your Age</th>
<td><input type="text" size="3" maxlength="3"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table></form><script>
function Validate() {
var valid = false;
var name = document.forms[0].elements[0].value.trim();
var age = document.forms[0].elements[1].value.trim();
var name_re = /^[A-Z][a-zA-Z '.-]+$/; // Name starts with capital, letters/spaces/dot/dash allowed
var age_re = /^\d+$/; // Age must be digits only
if (name.match(name_re)) {
if (age.match(age_re)) {

Department of Computer Science, ADC-GDV Page-6


II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.com
valid = true;
} else {
alert("Age must be numeric!");
}
} else {
alert("Name must start with a capital letter and contain only letters, spaces, dots, apostrophes, or hyphens.");
}
return valid;
}</script></body>
</html>
Q. Explain how messages and confirmations can be done in JavaScript?
JavaScript provides three built-in window types that can be used from application code. These are useful when we
need information from visitors to our site.
prompt() – Input from the User: To ask the user to enter some information (like their name, age, etc.).
 Syntax: prompt("Message", "Default value");
o A small window appears with a message.
o The user types something into the input box.
o The input is returned to the program.
Example: var name = prompt("Enter your name:", "John");
alert("Hello, " + name);
confirm() – Yes or No Option: To ask the user to confirm an action (e.g., "Are you sure you want to delete this?").
 Syntax: confirm("Message");
o Shows a message with OK and Cancel buttons.
o Returns true if the user clicks OK, false if Cancel.
Example: var result = confirm("Are you sure you want to leave?");
if(result) {
alert("You chose OK.");
}
else {
alert("You cancelled the action.");
}
alert() – Simple Message: To show a simple message or warning to the user.
 Syntax: alert("Message");
o Displays a popup with a message and an OK button.
o User must click OK to continue.
Example: alert("This is a warning message!");
<html>
<head>
<script language = "javascript">
<!--
prompt ("Enter Your name", "");
confirm ("Are you sure?");
alert("A warning");
//-->
</script></head></html>
Q. Explain about Status bar with example?
The browsers status bar as part of the site. Text strings can be displayed in the status bar but should be used with care. The
status bar usually displays helpful information about the operation of the browser.
Example:
<html>
<head><script language="javascript">
function Init(){
self.status "Hello":
}
</script></head>
<body onLoad="Init()">
<h1>And the Status Bar Says...</h1>
</body></html>
self: The script used the keyword self. Sometimes the script needs to act upon the browser window in which it is running.
Other times objects need to change their own parameters. In both cases self is used so that the object can identify itself or its
browser.
Q. Explain about Rollover buttons in DHTML?
A. The most common usage of dynamic HTML, and one that we are bound to have seen, is the image rollover. The technique
is used to give visual feedback about the location of the mouse cursor by changing the images on the pages as the mouse
moves over them.
The script code doesn't directly manipulate the image. The Java Script rollover is far simple because it uses two images files,
which it swaps between as the mouse is moved. One image is created for the inactive state when the mouse is not over it. A
second image is created for the active state when the mouse cursor is placed over it
<html>
<head> <title> Show image rollover with mouse event. </title></head>
<body>

Department of Computer Science, ADC-GDV Page-7


II YEAR BCA (DS) WEB TECHNOLOGY kumar.nagisetty@gmail.com
<h2> Showing image rollover with mouse event. </h2>
<h4> Rollover on the below image to change the styles of the image. </h4>
<img src="C:\Users\PC\Desktop\888.jpg" style="height:100px;width:100px;" id="demo" name="demo" alt="demo Image">
<script>
let dI = document.getElementById("demo");
dI.addEventListener( "mouseover", function () {document.demo.style = "height:200px; width:200px";});
dI.addEventListener( "mouseout", function () {document.demo.style = "height:100px; width:100px;"})
</script>
</body></html>
Q. Explain the concept of Moving images with examples?
A. The moving images is the actually moving is a layer of content. Images (layers) can move around repeatedly but doing so
takes up processor cycles. If our images only move for a restricted amount of time such as when the page is first loaded or
when the user specifically triggers the event. Each layer can be positioned on the screen by changing the offset of the top left
corner of the layer.
The following is an illustration which combines the use of JavaScript functions and positioning attribute of the style sheet to
move an object in a web document.
<html>
<head>
<title>Moving Images</title>
<style>
#change {
position: relative;
left: 0px;
}
</style>
</head>
<body>
<h2>Click the buttons to move the image</h2>
<div id="change">
<img src="888.jpg" height="400" width="400" id="myImage">
</div>
<form>
<input type="button" value="Move" onclick="move()">
<input type="button" value="Back" onclick="back()">
</form>
<script>
let change = document.getElementById("change");
let position = 0;
let changeid;
function move() {
if (position < 600) {
position += 5;
change.style.left = position + "px";
changeid = setTimeout(move, 50);
}
}
function back() {
clearTimeout(changeid);
position = 0;
change.style.left = position + "px";
}
</script>
</body>
</html>

Department of Computer Science, ADC-GDV Page-8

You might also like