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

CS8651 Notes 005-2 Edubuzz360

The document discusses JavaScript date objects and methods for getting and setting date values. It provides examples of using Date methods like getFullYear(), getMonth(), getDate() as well as setFullYear(), setMonth(), setDate(). It also discusses the JavaScript window and document objects and lists common methods for both.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

CS8651 Notes 005-2 Edubuzz360

The document discusses JavaScript date objects and methods for getting and setting date values. It provides examples of using Date methods like getFullYear(), getMonth(), getDate() as well as setFullYear(), setMonth(), setDate(). It also discusses the JavaScript window and document objects and lists common methods for both.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

www.edubuzz360.

com

UNIT II - CLIENT SIDE PROGRAMMING


Java Script: An introduction to JavaScript – JavaScript DOM Model – Date and
Objects – Regular Expressions – Exception Handling – Validation – Built-in objects –
Event Handling – DHTML with JavaScript – JSON introduction – Syntax – Function
Files – Http Request – SQL.
PART - A
Q.No Questions
1. Evaluate various Java Script Object models.
2. Define DOM.
Give any four methods of Date objects.

JavaScript Get Date Methods


These methods can be used for getting information from a date object:

Method Description

getFullYear() Get the year as a four digit number (yyyy)

getMonth() Get the month as a number (0-11)

getDate() Get the day as a number (1-31)

getHours() Get the hour (0-23)

getMinutes() Get the minute (0-59)


3.
getSeconds() Get the second (0-59)

getMilliseconds() Get the millisecond (0-999)

getTime() Get the time (milliseconds since January 1, 1970)

getDay() Get the weekday as a number (0-6)

Date.now() Get the time. ECMAScript 5.

JavaScript Set Date Methods


Set Date methods let you set date values (years, months, days, hours, minutes, seconds,
milliseconds) for a Date Object.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

Set Date Methods


Set Date methods are used for setting a part of a date:

Method Description

setDate() Set the day as a number (1-31)

setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since January 1,


1970)

Write the JavaScript methods to retrieve the data and time based on the
computer locale.

<script>

// Use of Date.now() function


var d = Date(Date.now());

// Converting the number of millisecond in date string


4. a = d.toString()

// Printing the current date


document.write("The current date is: " + a)

</script>

OUTPUT
The current date is: Thu Jan 09 2020 20:35:39 GMT+0530 (India Standard Time)
Can you list the different methods defined in document and window object
5. of JavaScript.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

Window Object
The window object represents an open window in a browser.

Window Object Methods


Method Description

alert() Displays an alert box with a message and an


OK button

atob() Decodes a base-64 encoded string

blur() Removes focus from the current window

btoa() Encodes a string in base-64

clearInterval() Clears a timer set with setInterval()

clearTimeout() Clears a timer set with setTimeout()

close() Closes the current window

confirm() Displays a dialog box with a message and an


OK and a Cancel button

focus() Sets focus to the current window

getComputedStyle() Gets the current computed CSS styles applied


to an element

getSelection() Returns a Selection object representing the


range of text selected by the user

matchMedia() Returns a MediaQueryList object representing


the specified CSS media query string

moveBy() Moves a window relative to its current


position

moveTo() Moves a window to the specified position

open() Opens a new browser window

print() Prints the content of the current window

prompt() Displays a dialog box that prompts the visitor


for input

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

requestAnimationFrame() Requests the browser to call a function to


update an animation before the next repaint

resizeBy() Resizes the window by the specified pixels

resizeTo() Resizes the window to the specified width and


height

scroll() Deprecated. This method has been replaced


by the scrollTo() method.

scrollBy() Scrolls the document by the specified number


of pixels

scrollTo() Scrolls the document to the specified


coordinates

setInterval() Calls a function or evaluates an expression at


specified intervals (in milliseconds)

setTimeout() Calls a function or evaluates an expression


after a specified number of milliseconds

stop() Stops the window from loading

Document Object Model


1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object

 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

 According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document."

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

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.

getElementsByTagName() returns all the elements having the


given tag name.

getElementsByClassName() returns all the elements having the


given class name.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

Name which parser is best in parsing in large size documents. Why?


6.

Summarize benefits of using JavaScript code in an HTML document.

Advantages of JavaScript
The merits of using JavaScript are −
 Less server interaction − You can validate user input before sending the page off to the server. This
saves server traffic, which means less load on your server.
7.
 Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have
forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user hovers over them with
a mouse or activates them via the keyboard.
 Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and
sliders to give a Rich Interface to your site visitors.

Predict the need for client and server side scripting.

Client-side scripting (embedded scripts) is code that exists inside the client’s
HTML page. This code will be processed on the client machine and the HTML
page will NOT perform a PostBack to the web-server. Traditionally, client-side
scripting is used for page navigation, data validation and formatting. The language
used in this scripting is JavaScript. JavaScript is compatible and is able to run on
any internet browser.

The two main benefits of client-side scripting are:

8. 1. The user’s actions will result in an immediate response because they don’t require
a trip to the server.

2. Fewer resources are used and needed on the web-server.

Server-side scripting is a technique used in web development which involves


employing scripts on a web server which produce a response customized for each user's
(client's) request to the website. The alternative is for the web server itself to deliver a static
web page.

The client-side script executes the code to the client side which is visible to the users while
a server-side script is executed in the server end which users cannot see.

9. Interpret how exceptions are handled in Java script.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

The try...catch...finally Statement


The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you
cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax –
<script type = "text/javascript">
<!--
try {
// Code to run
[break;]
}

catch ( e ) {
// Code to run if an exception occurs
[break;]
}

[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

The try block must be followed by either exactly one catch block or one finally block
(or one of both). When an exception occurs in the try block, the exception is placed in e and
the
catch block is executed. The optional finally block executes unconditionally after try/catch.
Examples
Here is an example where we are trying to call a non-existing function which in turn is raising
an exception. Let us see how it behaves without try...catch−
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

</script>
</head>

<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>

Define JavaScript statement with an example.

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

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":
<!DOCTYPE html>
<html>
<body>
10. <h2>JavaScript Statements</h2>

<p>In HTML, JavaScript statements are executed by the browser.</p>

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

<script>

document.getElementById("demo").innerHTML = "Hello Dolly.";

</script>

</body>

</html>

OUTPUT

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

JavaScript Statements

In HTML, JavaScript statements are executed by the browser.

Hello Dolly.

Point out any two techniques of event programming.


What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons
to close windows, messages to be displayed to users, data to be validated, and virtually any
other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here
we will see a few examples to understand a relation between Event and JavaScript −

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of
11.
his mouse. You can put your validation, warning etc., against this event type.
Example
Try the following example.
<html>

<head>

<script type = "text/javascript">

<!--

function sayHello() {

alert("Hello World")

//-->

</script>

</head>

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

<body>

<p>Click the following button and see result</p>

<form>

<input type = "button" onclick = "sayHello()" value = "Say Hello" />

</form>

</body>

</html>

Example 2
<!doctype html>
<html>
<head>
<script>
function hov() {
var e = document.getElementById('hover');
e.style.display = 'none';
}
</script>
</head>
<body>
<div id="hover" onmouseover="hov()"
style="background-color:green;height:200px;width:200px;">
</div>
</body>
</html>

OUTPUT
Before mouse is taken over green square-

Green square gets disappear after mouse is taken over it.


What is DHTML?
DHTML
12.
DHTML stands for Dynamic HTML, it is totally different from HTML. The DHTML make
use of Dynamic object model to make changes in settings and also in properties and methods.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

DHTML allows different scripting languages in a web page to change their variables, which
enhance the effects, looks and many others functions after the whole page have been fully
loaded or under a view process, or otherwise static HTML pages on the same.
DHTML is used to create interactive and animated web pages that are generated in real-time,
also known as dynamic web pages so that when such a page is accessed, the code within the
page is analyzed on the web server and the resulting HTML is sent to the client’s web
browser.

Differentiate HTML and DHTML


Some differences between HTML and DHTML:

 HTML is a mark-up language, while DHTML is a collection of technology.


 DHTML creates dynamic web pages, whereas HTML creates static web pages.
 DHTML allows including small animations and dynamic menus in Web pages.
 DHML used events, methods, properties to insulate dynamism in HTML Pages.
 DHML is basically using JavaScript and style sheets in an HTML page.
 HTML sites will be slow upon client-side technologies, while DHTML sites will be fast
enough upon client-side technologies.
13.  HTML creates a plain page without any styles and Scripts called as HTML. Whereas,
DHTML creates a page with HTML, CSS, DOM and Scripts called as DHTML.
 HTML cannot have any server side code but DHTML may contain server side code.
 In HTML, there is no need for database connectivity, but DHTML may require
connecting to a database as it interacts with user.
 HTML files are stored with .htm or .html extension, while DHTML files are stored with
.dhtm extension.
 HTML does not require any processing from browser, while DHTML requires
processing from browser which changes its look and feel.

Point out the key features of DHTML.

Key Features: Following are the some major key features of DHTML:
 Tags and their properties can be changed using DHTML.
 It is used for real-time positioning.
 Dynamic fonts can be generated using DHTML.
 It is also used for data binding.
14.
 It makes a webpage dynamic and be used to create animations, games, applications along
with providing new ways of navigating through websites.
 The functionality of a webpage is enhanced due to the usage of low-bandwidth effect by
DHTML.
 DHTML also facilitates the use of methods, events, properties, and codes.

Classify the data types in JSON


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to
read and write. ... JSON is built on two structures: A collection of name/value pairs. In various
15.
languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative
array.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

JSON Data Types. At the granular level, JSON consist of 6 data types. First four data types (string,
number, boolean and null) can be referred as simple data types. Other two data types (object and
array) can be referred as complex data types.

How to convert text into a JavaScript object using JSON?


Converting JSON text to JavaScript Object

JSON (JavaScript Object Notation) is a lightweight data-interchange format. As its


name suggests, JSON is derived from the JavaScript programming language, but it’s
available for use by many languages including Python, Ruby, PHP, and Java and
hence, it can be said as language-independent. For humans, it is easy to read and
write and for machines, it is easy to parse and generate. It is very useful for storing
and exchanging data.

A JSON object is a key-value data format that is typically rendered in curly braces.
JSON object consist of curly braces ( { } ) at the either ends and have key-value pairs
inside the braces. Each key-value pair inside braces are separated by comma (, ).
JSON object looks something like this :
{
"key":"value",
"key":"value",
"key":"value",

16. }
Example for a JSON object :

{
"rollno":101",
"name":"Mayank",
"age":20,
}

Conversion of JSON text to Javascript Object

JSON text/object can be converted into Javascript object using the


function JSON.parse().

var object1 = JSON.parse('{"rollno":101, "name":"Mayank", "age":20}');

For getting the value of any key from a Javascript object, we can use the values
as: object1.rollno

17. Evaluate the syntax to create arrays in JSON.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

JavaScript | JSON Arrays


The JSON Arrays is similar to JavaScript Arrays.
Syntax of Arrays in JSON Objects:
// JSON Arrays Syntax

{
"name":"Peter parker",
"heroName": "Spiderman",
"friends" : ["Deadpool", "Hulk", "Wolverine"]
}
Accessing Array Values:
The Array values can be accessed using the index of each element in an Array.

EXAMPLE

<script>
var myObj, i, x = "";
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
};

for (i in myObj.cars) {
x += myObj.cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;
</script>

OUTPUT

Looping through an array using a for in loop:

Ford
BMW
Fiat
How will you make a request with JSON?

What is a JSON request?


JavaScript Object Notation (JSON) is a standard text-based format for representing
structured data based on JavaScript object syntax. It is commonly used for
18. transmitting data in web applications (e.g., sending some data from the server to the
client, so it can be displayed on a web page, or vice versa).

jQuery getJSON() Method

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

The jQuery getJSON() method sends asynchronous http GET request to the server and retrieves
the data in JSON format by setting accepts header to application/json, text/javascript. This is
same as get() method, the only difference is that getJSON() method specifically retrieves JSON
data whereas get() method retrieves any type of data. It is like shortcut method to retrieve JSON
data. Syntax:

$.getJSON(url,[data],[callback]);

Parameter Description:

 url: request url from which you want to retrieve the data
 data: JSON data to be sent to the server as a query string
 callback: function to be executed when request succeeds

The following example shows how to retrieve JSON data using getJSON() method.

Example: jQuery getJSON() Method

$.getJSON('/jquery/getjsondata', {name:'Steve'}, function (data, textStatus, jqXHR){


$('p').append(data.firstName);
});

<p></p>

OUTPUT

jQuery get() method demo

Steve
Define DDL and DML
DDL(Data Definition Language) : DDL or Data Definition Language actually consists of the
SQL commands that can be used to define the database schema. It simply deals with
descriptions of the database schema and is used to create and modify the structure of
database objects in the database.

Examples of DDL commands:


 CREATE – is used to create the database or its objects (like table, index, function,
19.
views, store procedure and triggers).
 DROP – is used to delete objects from the database.
 ALTER-is used to alter the structure of the database.
 TRUNCATE–is used to remove all records from a table, including all spaces allocated
for the records are removed.
 COMMENT –is used to add comments to the data dictionary.
 RENAME –is used to rename an object existing in the database

Write SQL query to find minimum and maximum marks in a table.

20. DML(Data Manipulation Language) : The SQL commands that deals with the manipulation
of data present in the database belong to DML or Data Manipulation Language and this
includes most of the SQL statements.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

Examples of DML:
 INSERT – is used to insert data into a table.
 UPDATE – is used to update existing data within a table.
 DELETE – is used to delete records from a database table.

PART - B
Q.No Questions
i) Examine variables and data types in JavaScript.
Variables in JavaScript:
Variables in JavaScript are containers which hold reusable data. It is the basic unit of
storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on
the variable effects that memory location.
 In JavaScript, all the variables must be declared before they can be used.

JavaScript variables are containers for storing data values.

In this example, x, y, and z, are variables:

Examples
var x = 5; var price1 = 5;
var y = 6; var price2 = 6;
var z = x + y; var total = price1 + price2;

1.

Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var keyword:

var carName;

After the declaration, the variable has no value (technically it has the value of undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

var carName = "Volvo";

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

EXAMPLE
<script> OUTPUT
var carName = "Volvo"; JavaScript Variables
document.getElementById("demo").innerHTML
= carName;
</script> Create a variable, assign a value to it,
and display it:

Volvo

ii) Give various Operators in JavaScript.

JavaScript Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers:

Operator Description Example

+ Addition var x = 5;
var y = 2;
var z = x + y;

- Subtraction var x = 5;
var y = 2;
var z = x - y;

* Multiplication var x = 5;
var y = 2;
var z = x * y;

** Exponentiation
(ES2016)

/ Division

% Modulus (Division
Remainder)

++ Increment

-- Decrement

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.

Operator Example Same As

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

**= x **= y x = x ** y

The addition assignment operator (+=) adds a value to a variable.

Assignment
var x = 10;
x += 5;

JavaScript String Operators


The + operator can also be used to add
(concatenate) strings. The += assignment operator can also be used
to add (concatenate) strings:
Example
var txt1 = "John"; Example
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2; var txt1 = "What a very ";
txt1 += "nice day";
The result of txt3 will be:
The result of txt1 will be:
John Doe
What a very nice day
When used on strings, the + operator is called
the concatenation operator.

JavaScript Comparison Operators


Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

JavaScript Logical Operators


Operator Description

&& logical and

|| logical or

! logical not

JavaScript Type Operators


Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of


an object type
Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to a JavaScript number.
Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< Zero fill left shift 5 << 1 0101 << 1 1010 10

>> Signed right shift 5 >> 1 0101 >> 1 0010 2

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

>>> Zero fill right 5 >>> 1 0101 >>> 1 0010 2


shift

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010

(i) Summarize about DOM Model.


What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style of
a document."

The W3C DOM standard is separated into 3 different parts:

 Core DOM - standard model for all document types


 XML DOM - standard model for XML documents
2.  HTML DOM - standard model for HTML documents

JavaScript HTML DOM


With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.

The HTML DOM (Document Object Model)


When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

(ii) Describe the concepts of Popup Boxes.

JavaScript Popup Boxes


JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

JavaScript Popup Boxes


JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box Syntax Example


alert("I am an alert
An alert box is often window.alert("sometext"); box!");
used if you want to The window.alert() method can be written
make sure information without the window prefix
comes through to the
user.

When an alert box


pops up, the user will
have to click "OK" to
proceed

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

Confirm Box Syntax Example


if (confirm("Press a
When a confirm box window.confirm("sometext"); button!")) {
pops up, the user will txt = "You pressed
have to click either The window.confirm() method can be OK!";
"OK" or "Cancel" to written without the window prefix. } else {
proceed. txt = "You pressed
Cancel!";
If the user clicks }
"OK", the box
returns true. If the user
clicks "Cancel", the
box returns false.

Prompt Box Syntax Example


var person =
A prompt box is often window.prompt("sometext","defaultText"); prompt("Please enter
used if you want the your name", "Harry
user to input a value The window.prompt() method can be Potter");
before entering a page. written without the window prefix.
if (person == null ||
If the user clicks "OK" person == "") {
the box returns the txt = "User cancelled
input value. If the user the prompt.";
clicks "Cancel" the } else {
box returns null. txt = "Hello " + person
+ "! How are you
today?";
}

(i) Write short notes on Date and Objects.


The Date Object. The Date object is a built-in object in JavaScript that stores the date and
time. It provides a number of built-in methods for formatting and managing that data. By
default, a new Date instance without arguments provided creates an object corresponding to
the current date and time

The Date Object


3.
The Date object is a built-in object in JavaScript that stores the date and time. It
provides a number of built-in methods for formatting and managing that data.

By default, a new Date instance without arguments provided creates an object


corresponding to the current date and time. To demonstrate JavaScript’s Date, let’s
create a variable and assign the current date to it.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

EXAMPLE

now.js

// Set variable to current date and time


const now = new Date();

// View the output


now;
Output
Wed Oct 18 2017 12:41:34 GMT+0000 (UTC)

Date Creation Output


new Date() Current date and time

Creates date based on milliseconds since


new Date(timestamp)
Epoch time

new Date(date string) Creates date based on date string

new Date(year, month,


Creates date based on specified date and
day, hours, minutes,
seconds, milliseconds) time

(ii) Explain in detail about Regular expressions.

A JavaScript Regular Expression (or Regex) is a sequence of characters that we can utilize to
work effectively with strings. Using this syntax, we can:

 search for text in a string

 replace substrings in a string

 extract information from a string

(i) Describe the control statements in Java.


Conditional Statements
4.
Very often when you write code, you want to perform different actions for
different decisions.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition


is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use switch to specify many alternative blocks of code to be executed

JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each
time with a different value.

Often this is the case when working with arrays:

<script>

var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

var text = "";

var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";

document.getElementById("demo").innerHTML = text;

</script>

OUTPUT
JavaScript For Loop

BMW
Volvo
Saab
Ford
Fiat
Audi

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

(ii) Discuss any two validation functions in java script.

(i) Write a Java script to find the Prime number between 1 and 100.

<html>
<head>
<title>JavaScript Prime</title>
</head>

<body>
<script>
for (var limit = 1; limit <= 20; limit++) {
var a = false;
for (var i = 2; i <= limit; i++) {
if (limit%i===0 &amp;&amp; i!==limit) {
a = true;
}
}
if (a === false) {
5. document.write("<br>"+limit);
}
}
</script>
</body>
</html>

(ii) Write a Java Script to find factorial of a given number.

function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}

alert( factorial(5) ); // 120

(i) Demonstrate a java script for displaying the context menu.

(ii) Demonstrate a java script to display the welcome message


using the alert whenever button of a html form is pressed.
<html>
<head>
6. <title>Display Alert Message on Button Click Event.</title>
<script type="text/javascript">
function showMessage(){
alert("Welcome friends, You pressed the Button.");
}
</script>
</head>
<body>

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

<center>
<h1>Display Alert Message on Button Click Event.</h1>
<b>Click on button to display message: </b><br><br>
<input type="button" id="btnShowMsg" value="Click Me!"
onClick='showMessage()'/>
</center>
</body>

</html>

Result

Welcome friends, You pressed the Button.

(i) Evaluate how DOM Nodes and Trees can be used.

What is the purpose of HTML DOM Node Tree?

- HTML DOM view the HTML document with a tree structure format and it consists of root
node and child nodes.

- The node-tree is being accessed using the tree formation and the structure in which the
elements get created.

- The contents that are used being modified or removed using the new elements and it can be
created within the limitations.

- The structure consists of a document that is the root and within it Root element <html> from
where the tree starts.
7.
- It consists of sub-elements like <head> and <body> and other text and attributes written in
the HTML format.

(ii) Evaluate the way of Traversing and modifying a DOM Tree.

(i) Discuss the concepts of Registering Event handlers.


8. As mentioned above, events are actions or occurrences that happen in the system you are
programming — the system produces (or "fires") a signal of some kind when an event occurs,

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

and also provides a mechanism by which some kind of action can be automatically taken (that
is, some code running) when the event occurs. For example in an airport when the runway is
clear for a plane to take off, a signal is communicated to the pilot, and as a result, they
commence piloting the plane.

In the case of the Web, events are fired inside the browser window, and tend to be
attached to a specific item that resides in it — this might be a single element, set of
elements, the HTML document loaded in the current tab, or the entire browser
window. There are a lot of different types of events that can occur, for example:

 The user clicking the mouse over a certain element or hovering the cursor over a
certain element.
 The user pressing a key on the keyboard.
 The user resizing or closing the browser window.
 A web page finishing loading.
 A form being submitted.
 A video being played, or paused, or finishing play.
 An error occurring.
Each available event has an event handler, which is a block of code (usually a JavaScript
function that you as a programmer create) that will be run when the event fires. When such a
block of code is defined to be run in response to an event firing, we say we are registering an
event handler. Note that event handlers are sometimes called event listeners — they are
pretty much interchangeable for our purposes, although strictly speaking, they work together.
The listener listens out for the event happening, and the handler is the code that is run in
response to it happening.
In the following example, we have a single <button>, which when pressed, makes the
background change to a random color:

<button>Change color</button>

The JavaScript looks like so:

const btn = document.querySelector('button');

function random(number) {
return Math.floor(Math.random() * (number+1));
}

btn.onclick = function() {
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' +
random(255) + ')';
document.body.style.backgroundColor = rndCol;
}

(ii) Discuss the concepts of Event Handling.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

JavaScript Events
HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events
An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time
is?</button>

OUTPUT
Sun Jan 12 2020 06:00:41 GMT+0530 (India Standard Time)

In the example above, the JavaScript code changes the content of the element with id="demo".

Analyze a web page to create a clock with timing event.


function showTime(){
9. var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

var s = date.getSeconds(); // 0 - 59
var session = "AM";

if(h == 0){
h = 12;
}

if(h > 12){


h = h - 12;
session = "PM";
}

h = (h < 10) ? "0" + h : h;


m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;

var time = h + ":" + m + ":" + s + " " + session;


document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;

setTimeout(showTime, 1000);

showTime();

<html>
<head>
<title>Digital Clock</title>
<style>
#clock{
color:#F0F;
}

</style>
</head>
<body>
<script>
function digclock()
{
var d = new Date()
var t = d.toLocaleTimeString()

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

document.getElementById("clock").innerHTML = t
}

setInterval(function(){digclock()},1000)

</script>
Digital Clock
<div id="clock">

</div>
</body>
</html>

OUTPUT
Output :

Digital Clock
5:54:26 PM

(i) Write short notes on DHTML with JavaScript.

Dynamic HyerText Markup Language (DHTML) is a combination of Web development


technologies used to create dynamically changing websites. Web pages may include
animation, dynamic menus and text effects. The technologies used include a
combination of HTML, JavaScript or VB Script,
CSS and the document object model (DOM).

Designed to enhance a Web user’s experience, DHTML includes the following


features:

 Dynamic content, which allows the user to dynamically change Web page
content
10.  Dynamic positioning of Web page elements
 Dynamic style, which allows the user to change the Web page’s color, font,
size or content

EXAMPLE
<! DOCTYPE html PUBLIC "-//abc//DTD XHTML 1.1//EN"
"http://www.abc.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.abc.org/1999/xhtml">
<head>
<title>DHTML example</title>
<script type="text/JavaScript">
function greet_user()
{
var name=document.getElementById(“userName”).value;

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

if(name==””)
{
alert(“Welcome”+name);
}
else
{
alert(“Please provide User Name”)
}
}
</script>
</head>
<body>
<table border=”1” cellspacing=”3”>
<tr>
<td colspan=”2”><h6> Please Enter Your Name </h6></td>
</tr>
<tr>
<td><h4>User Name </h4></td>
<td><input type=”text” id=”userName” ></td>
</tr>
<tr>
<td colspan=”2”><input type=”button” value=”Submit”
onclick=”greet_user()”/>
</table>
</body>
</html>
(ii) Classify moving elements.

Explain the concept of JSON with example.

JSON is a format for storing and transporting data.

JSON is often used when data is sent from a server to a web page.

What is JSON?

11.  JSON stands for JavaScript Object Notation


 JSON is a lightweight data interchange format
 JSON is language independent *
 JSON is "self-describing" and easy to understand

* The JSON syntax is derived from JavaScript object notation syntax, but the
JSON format is text only. Code for reading and generating JSON data can be
written in any programming language.

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

JSON Example

This JSON syntax defines an employees object: an array of 3 employee


records (objects):

JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}

Describe in detail about JSON Objects and Arrays.

JSON Arrays
Arrays as JSON Objects

Example
[ "Ford", "BMW", "Fiat" ]

Arrays in JSON are almost the same as arrays in JavaScript.

In JSON, array values must be of type string, number, object, array, boolean
or null.

In JavaScript, array values can be all of the above, plus any other valid
JavaScript expression, including functions, dates, and undefined.
12.

Arrays in JSON Objects

Arrays can be values of an object property:

Example
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

Accessing Array Values

You access the array values by using the index number:

Example
x = myObj.cars[0];

Looping Through an Array

You can access array values by using a for-in loop:

Example
for (i in myObj.cars) {
x += myObj.cars[i];
}
OUTPUT

Looping through an array using a for in loop:

Ford
BMW
Fiat
Analyze about Function files and Http Request with sample
program.

<!doctype html>
<title>Example</title>

<script>
// Store XMLHttpRequest and the JSON file location in variables
var xhr = new XMLHttpRequest();
var url = "https://www.quackit.com/json/tutorial/artists.txt";

// Called whenever the readyState attribute changes


13.
xhr.onreadystatechange = function() {

// Check if fetch request is done


if (xhr.readyState == 4 && xhr.status == 200) {

// Parse the JSON string


var jsonData = JSON.parse(xhr.responseText);

// Call the showArtists(), passing in the parsed JSON string


showArtists(jsonData);
}
};

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

// Do the HTTP call using the url variable we specified above


xhr.open("GET", url, true);
xhr.send();

// Function that formats the string with HTML tags, then outputs the result
function showArtists(data) {
var output = "<ul>"; // Open list
var i;

// Loop through the artists, and add them as list items


for (var i in data.artists) {
output += "<li>" + data.artists[i].artistname + " (Born: " + data.artists[i].born + ")</li>";
}

output += "</ul>"; // Close list

// Output the data to the "artistlist" element


document.getElementById("artistList").innerHTML = output;
}
</script>

<!-- The output appears here -->


<div id="artistList"></div>
OUTPUT

 Leonard Cohen (Born: 1934)


 Joe Satriani (Born: 1956)
 Snoop Dogg (Born: 1971)

Summarize about
(i) SQL Data Definition Commands
Examples of Sql DDL commands are

 CREATE – Create an object. I mean, create a database, table, triggers,


index, functions, stored procedures, etc.
 DROP – This SQL DDL command helps to delete objects. For example, delete tables,
delete a database, etc.
 ALTER – Used to alter the existing database or its object structures.
14.  TRUNCATE – This SQL DDL command removes records from tables
 RENAME – Renaming the database objects

(ii) Data Manipulation Commands.


Examples of DML commands are

 SELECT – This SQL DML command select records or data from a table
 INSERT – Insert data into a database table.
 UPDATE – This SQL DML command will update existing records within a table

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

 DELETE – Delete unwanted records from a table

PART – C
Q.No Questions
Analyze the merits and demerits of DOM parser with neat example.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var str = "<root><customer name='John' address='Chicago'></customer></root>";
function CreateXMLDocument () {
var xmlDoc = null;
if (window.DOMParser) {
var parser = new DOMParser ();
xmlDoc = parser.parseFromString (str, "text/xml");
} else if (window.ActiveXObject) {
xmlDoc = new ActiveXObject ("Microsoft.XMLDOM");
xmlDoc.async = false;
1.
xmlDoc.loadXML (str);
}

var customerNode = xmlDoc.getElementsByTagName ("customer")[0];


var customerName = customerNode.getAttribute ("name");
alert ("The name of the first customer is " + customerName);
}
</script>
</head>
<body>
<button onclick="CreateXMLDocument ();">Create an XML document from a
string</button>
</body>
</html>

Consider a java script and HTML to create a page with two panes.
The first pane (on left) should have a text area where HTML code
can bet typed by the user. The pane on the left should have a text
area where HTML code can be typed by the user. The pane on the
2. right side should display the preview of the HTML code typed by
the user, as it would be seen on the browser.

Develop a DHTML program to handle the user click event.


3.
<!DOCTYPE html>
<html>

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

<body>

<p>Click the button to display the time.</p>

<button onclick="getElementById('demo').innerHTML=Date()">What is the


time?</button>

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

</body>
</html>

OUTPUT

Click the button to display the time.

What is the time?

Sat Jan 11 2020 22:36:24 GMT+0530 (India Standard Time)

Formulate a JavaScript program that work with JSON.

JSON Object Syntax


Example
{ "name":"John", "age":30, "car":null }

 JSON objects are surrounded by curly braces {}.


 JSON objects are written in key/value pairs.
 Keys must be strings, and values must be a valid JSON data type (string, number,
object, array, boolean or null).
 Keys and values are separated by a colon.
 Each key/value pair is separated by a comma.
4.
Accessing Object Values

You can access the object values by using dot (.) notation:

Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;

You can also access the object values by using bracket ([]) notation:

Example

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

myObj = { "name":"John", "age":30, "car":null };


x = myObj["name"];

Looping an Object

You can loop through object properties by using the for-in loop:

Example

In a for-in loop, use the bracket notation to access the property values:

Example
<!DOCTYPE html>
<html>
<body>

<p>How to loop through all properties in a JSON object.</p>

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

<script>
var myObj, x;
myObj = {"name":"John", "age":30, "car":null};
for (x in myObj) {
document.getElementById("demo").innerHTML += x + " " + myObj[x] + "<br>";
}
</script>

</body>
</html

OUTPUT

How to loop through all properties in a JSON object.

name John
age 30
car null

Nested JSON Objects

Values in a JSON object can be another JSON object.

Example
myObj = {
"name":"John",

https://play.google.com/store/apps/details?id=com.sss.edubuzz360
www.edubuzz360.com

"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}

You can access nested JSON objects by using the dot notation or bracket notation:

Example
x = myObj.cars.car2;
// or:
x = myObj.cars["car2"];

OUTPUT

How to access nested JSON objects.

BMW
BMW

https://play.google.com/store/apps/details?id=com.sss.edubuzz360

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy