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

Unit 4th Javascript PDF

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

Unit 4th Javascript PDF

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

Hina Gojwari

CASET College

APPLIED COMPUTING II
(WEB DESIGNING)
UNIT- IV
Introduction to JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon). Let’s see the simple
example of creating object in JavaScript.

<script>

emp={id:102,name:"paul",salary:40000}

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

Output of the above example

102 paul 40000


Hina Gojwari
CASET College

2) By creating instance of Object


The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object. Let’s see the example of creating object
directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="paul";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output of the above example


101 paul 50000

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword. The this keyword refers to the
current object. The example of creating object by object constructor is given below.

<script>

function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary; }
e=new emp(103,"paul",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

Output of the above example


103 paul 30000
Hina Gojwari
CASET College

JavaScript Quering and setting properties / Getter and Setter

In this tutorial, you will learn about JavaScript getter and setter methods
with the help of examples.

In JavaScript, there are two kinds of object properties:

 Data properties

 Accessor properties

Data Property
Here's an example of data property that we have been using in the
previous tutorials.

const student = {

// data property
firstName: 'Monica';
};

Accessor Property
In JavaScript, accessor properties are methods that get or set the value of
an object. For that, we use these two keywords:

 get - to define a getter method to get the property value


 set - to define a setter method to set the property value
Hina Gojwari
CASET College

JavaScript Getter

In JavaScript, getter methods are used to access the properties of an


object. For example,

const student = {

// data property
firstName: 'Monica',

// accessor property(getter)
get getName() {
return this.firstName;
}
};

// accessing data property


console.log(student.firstName); // Monica

// accessing getter methods


console.log(student.getName); // Monica

// trying to access as a method


console.log(student.getName()); // error
Run Code

In the above program, a getter method getName() is created to access the


property of an object.

get getName() {
return this.firstName;
}

Note: To create a getter method, the get keyword is used.

And also when accessing the value, we access the value as a property.

student.getName;

When you try to access the value as a method, an error occurs.


Hina Gojwari
CASET College

console.log(student.getName()); // error

JavaScript Setter
In JavaScript, setter methods are used to change the values of an object.
For example,

const student = {
firstName: 'Monica',

//accessor property(setter)
set changeName(newName) {
this.firstName = newName;
}
};

console.log(student.firstName); // Monica

// change(set) object property using a setter


student.changeName = 'Sarah';

console.log(student.firstName); // Sarah
Run Code

In the above example, the setter method is used to change the value of an
object.

set changeName(newName) {
this.firstName = newName;
}

Note: To create a setter method, the set keyword is used.

As shown in the above program, the value of firstName is Monica .

Then the value is changed to Sarah .


Hina Gojwari
CASET College

student.changeName = 'Sarah';

Note: Setter must have exactly one formal parameter.

JavaScript Object.defineProperty()
In JavaScript, you can also use Object.defineProperty() method to add
getters and setters. For example,
const student = {
firstName: 'Monica'
}

// getting property
Object.defineProperty(student, "getName", {
get : function () {
return this.firstName;
}
});

// setting property
Object.defineProperty(student, "changeName", {
set : function (value) {
this.firstName = value;
}
});

console.log(student.firstName); // Monica

// changing the property value


student.changeName = 'Sarah';

console.log(student.firstName); // Sarah
Run Code

In the above example, Object.defineProperty() is used to access and


change the property of an object.
The syntax for using Object.defineProperty() is:
Hina Gojwari
CASET College

Object.defineProperty(obj, prop, descriptor)

The Object.defineProperty() method takes three arguments.


 The first argument is the objectName.

 The second argument is the name of the property.

 The third argument is an object that describes the property.

Remove Property from an Object


The delete operator deletes a property from an object:

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

delete person.age; // or delete person["age"];

// Before deletion: person.age = 50, after deletion, person.age =


undefined

The delete operator deletes both the value of the property and the property
itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no


effect on variables or functions.

Note: The delete operator should not be used on predefined JavaScript


object properties. It can crash your application.

Ways to Check If an Object Has a Property/Key


in JavaScript
In this post, you'll read 3 common ways to check for property or key
existence in a JavaScript object.
Hina Gojwari
CASET College

Note: In the post, I describe property existence checking, which is the


same as checking for key existence in an object.
Table of Contents
1. hasOwnProperty() method
2. in operator
3. Comparing with undefined
4. Summary

1. hasOwnProperty() method
Every JavaScript object has a special
method object.hasOwnProperty('myProp') that returns a boolean
indicating whether object has a property myProp.

In the following example, hasOwnProperty() determines the presence of


properties name and realName:
const hero = {
name: 'Batman'
};

console.log(hero.hasOwnProperty('name')); // => true


console.log(hero.hasOwnProperty('realName')); // => false

Open the demo.

hero.hasOwnProperty('name') returns true because the property name exists


in the object hero.

On the other side, hero doesn't have realName property.


Thus hero.hasOwnProperty('realName') returns false — denoting a missing
property.

The method name hasOwnProperty() suggests that it looks for the own
properties of the object. The own properties are those defined directly
upon the object.

This way hasOwnProperty() doesn't detect the toString — an inherited


method from the prototype object:
const hero = {
name: 'Batman'
};
Hina Gojwari
CASET College

console.log(hero.toString); // => function() {...}

console.log(hero.hasOwnProperty('toString')); // => false

Open the demo.

2. in operator
'myProp' in object also determines whether myProp property exists
in object.

Let's use in operator to detect the existence


of name and realName in hero object:
const hero = {
name: 'Batman'
};

console.log('name' in hero); // => true


console.log('realName' in hero); // => false

Open the demo.

'name' in hero evaluates to true because hero has a property name.

On the other side, 'realName' in hero evaluates


to false because hero doesn't have a property named 'realName'.

inoperator has a short syntax, and I prefer it


over hasOwnProperty() method.

The main difference between hasOwnProperty() method and in operator


is that the latter checks within own and inherited properties of the
object.

That's why, in contrast to hasOwnProperty(), the in operator detects


that hero object contains the inherited property toString:
const hero = {
name: 'Batman'
};

console.log(hero.toString); // => function() {...}

console.log('toString' in hero); // => true


console.log(hero.hasOwnProperty('toString')); // => false
Hina Gojwari
CASET College

3. Comparing with undefined


Accessing a non-existing property from an object results in undefined:
const hero = {
name: 'Batman'
};

console.log(hero.name); // => 'Batman'


console.log(hero.realName); // => undefined

hero.realName evaluates to undefined because realName property is missing.

Now you can see the idea: you can compare with undefined to
determine the existence of the property.
const hero = {
name: 'Batman'
};

console.log(hero.name !== undefined); // => true


console.log(hero.realName !== undefined); // => false

hero.name !== undefined evaluates to true, which shows the existence of


property.

On the other side, hero.realName !== undefined is false, which indicates


that realName is missing.

Comparing with undefined to detect the existence of property is a cheap


and dirty approach.

But be aware of false-negatives. If the property exists, but


has undefined value (case, however, rarely happening), comparing
against undefined evaluates incorrectly to false:
const hero = {
name: undefined
};

console.log(hero.name !== undefined); // => false

Even if the property name exists (but has undefined value), hero.name !==
undefined evaluates to false: which incorrectly indicates a missing
property.
Hina Gojwari
CASET College

4. Summary
There are mainly 3 ways to check if the properties or keys exist in an
object.

The first way is to invoke object.hasOwnProperty(propName). The method


returns true if the propName exists inside object, and false otherwise.

hasOwnProperty() searches only within the own properties of the object.

The second approach makes use of propName in object operator. The


operator evaluates to true for an existing property, and false otherwise.

inoperator looks for properties existence in


both own and inherited properties.

Finally, you can simply use object.propName !== undefined and compare
against undefined directly.

Serializing Objects

Object serialization is the process of converting an object’s state to a


string from which it can later be restored. ECMAScript 5 provides native
functions JSON.stringify() and JSON.parse() to serialize and restore
JavaScript objects. These functions use the JSON data interchange format.
JSON stands for “JavaScript Object Notation,” and its syntax is very
similar to that of JavaScript object and array literals:

o = {x:1, y:{z:[false,null,""]}}; // Define a test object


s = JSON.stringify(o); // s is
'{"x":1,"y":{"z":[false,null,""]}}'
p = JSON.parse(s); // p is a deep copy of o

The native implementation of these functions in ECMAScript 5 was


modeled very closely after the public-domain ECMAScript 3
implementation available at http://json.org/json2.js. For practical purposes,
the implementations are the same, and you can use these ECMAScript 5
functions in ECMAScript 3 with this json2.js module.
Hina Gojwari
CASET College

JSON syntax is a subset of JavaScript syntax, and it cannot represent all


JavaScript values. Objects, arrays, strings, finite numbers, true, false,
and null are supported and can be serialized and restored. NaN, Infinity,
and -Infinity are serialized to null. Date objects are serialized to ISO-
formatted date strings (see the Date.toJSON() function),
but JSON.parse() leaves these in string form and does not restore the
original Date object. Function, RegExp, and Error objects and
the undefined value cannot be serialized or
restored. JSON.stringify() serializes only the enumerable ...
Hina Gojwari
CASET College

JavaScript Arrays
An array is a special variable, which can hold more than one value:

const cars = ["Saab", "Volvo", "BMW"];

Why Use Arrays?


If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:

let car1 = "Saab";


let car2 = "Volvo";
let car3 = "BMW";

However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?

The solution is an array! An array can hold many values under a single
name, and you can access the values by referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

const array_name = [item1, item2, ...];

It is a common practice to declare arrays with the const keyword.

Learn more about const with arrays in the chapter: JS Array Const.

Example
const cars = ["Saab", "Volvo", "BMW"];

Spaces and line breaks are not important. A declaration can span multiple
lines:

const cars = [
"Saab",
"Volvo",
"BMW"
];
Hina Gojwari
CASET College

You can also create an array, and then provide the elements:

Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:

Example
const cars = new Array("Saab", "Volvo", "BMW");

The two examples above do exactly the same. There is no need to use new
Array(). For simplicity, readability and execution speed, use the array literal
method.

Accessing Array Elements


You access an array element by referring to the index number:

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0];

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:

cars[0] = "Opel";

Example :
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Hina Gojwari
CASET College

Arrays are Objects


Arrays are a special type of objects. The typeof operator in JavaScript
returns "object" for arrays. But, JavaScript arrays are best described as
arrays. Arrays use numbers to access its "elements". In this
example, person[0] returns John:

Array:
const person = ["John", "Doe", 46];

Objects use names to access its "members". In this


example, person.firstName returns John:

Object:
const person = {firstName:"John", lastName:"Doe", age:46};

The length Property


The length property of an array returns the length of an array (the number of
array elements).

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

The length property is always one more than the highest array index.

Accessing the First Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];

Accessing the Last Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[fruits.length - 1];
Hina Gojwari
CASET College

Looping Array Elements


One way to loop through an array, is using a for loop:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";


for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

You can also use the Array.forEach() function:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

Converting string to an array in JavaScript


The task we need to accomplish is converting an input string to an array in
JavaScript.
Whenever we try to break a string word into characters or a sentence into words –
splitting into arrays, we have some built-in methods to convert string to an array.
In this article, we will discuss how to convert the string to an array using different
methods in JavaScript.

Using the split() method


This method will split the string to an array of substrings. This will return the output
in a new array and will not change the existing string.
Split() method accepts 2 parameters and both are optional parameters, the first is
a separator. It will describe where each split should happen and this can be a string
or regular expression. If we didn’t pass any parameter, it will return the entire string
in the array.
Hina Gojwari
CASET College

The second parameter is limit, the input should an integer that will limit the number
of splits.

Example 1
Following is the example of converting a string to an array using the split() method

<!DOCTYPE html>

<html>

<title>Converting string to an array in JavaScript</title>

<head>

<script>

var string = "We are CASET College";

const arr1 = string.split(' ');

const arr2 = string.split('');

const arr3 = string.split(" ", 2)

document.write(arr1, "<br>", arr2, "<br>", arr3, "<br>");

let [first, second, third, fourth] = string.split(' ');

document.write(first, second, third, fourth);

</script>

</head>

<body>

</body>

</html>

O/p
We,are,CASET,College
W,e, ,a,r,e, ,C,A,S,E,T, ,C,o,l,l,e,g,e
We,are
WeareCASETCollege

Example 2

Split method with special characters


In the example below, the input sentence has some special characters in it. And we
have passed those special characters in split() method. Whenever there is a match
with those characters in the string, it will split the sentence there and remove the
special character in the output.
Hina Gojwari
CASET College

<!DOCTYPE html>
<html>
<title>Converting string to an array in JavaScript</title>
<head>
<script>
var string = "Oh, you are working CASET? that place is amazing! how can
i join there; is there any vacancy? please let me know.";
const array = string.split(/[.,!,?,;]/);
document.write(array);
</script>
</head>
<body>
</body>
</html>

O/p
Oh, you are working CASET, that place is amazing, how can i join there, is there
any vacancy, please let me know,

Using the Array.from() method


We can also perform the above task by using Array.from() method.
The Array.from() method will return an array as an output from any object having a
length property and also from any iterable object. It accepts a parameter object to
convert into an array.

Example
Following is the example, where we used Array.from() method to convert string to an
array −
<!DOCTYPE html>

<html>

<title>Converting string to an array in JavaScript</title>

<head>

<script>

let string = "CASET";

let arr = Array.from(string);

document.write(arr);

</script>

</head>

<body>

</body>

</html>
Hina Gojwari
CASET College

O/p
C,A,S,E,T

Using the spread operator(…)


The Spread(…) operator can expand the elements of an array or string as a series of values.
If we pass the string without the spread operator it will not expand the characters of the
string instead, it will print the whole string as a single element in an array.
let string = "hello world my name ";
let array = [string];
document.write.log(array); // output: ["hello world my name "]
So we can avoid this by using spread(…) operator. Using this spread operator, it will extract
the elements of the string as a series of values.

Example
Following is the example to convert string to an array −
<!DOCTYPE html>

<html>

<title>Converting string to an array in JavaScript</title>

<head>

<script>

let string = "Let's go to new york";

let arr = [...string];

document.write(arr);

</script>

</head>

<body>

</body>

</html>

O/p L,e,t,',s, ,g,o, ,t,o, ,n,e,w, ,y,o,r,k


Hina Gojwari
CASET College

Using the Object.assign() method


The Object.assign() method will copy all the properties from the source object to the target
object. It accepts two parameters, one is the target and the second is the source and it returns
the target object.
Following is the syntax of Object.assign() method −
Object.assign(target, sources)
Example
In the example below, we have declared the source object and passed the source as the
source parameter to the object.assign() and an empty array as the target parameter. This will
return the elements in the string into an array.
<!DOCTYPE html>

<html>

<title>Converting string to an array in JavaScript</title>

<head>

<script>

let string = "Hina is a cult classic";

let arr = Object.assign([], string);

document.write(arr);

</script>

</head>

<body>

</body>

</html>

O/p
H,i,n,a, ,i,s, ,a, ,c,u,l,t, ,c,l,a,s,s,i,c
Hina Gojwari
CASET College

JavaScript HTML DOM


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

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

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
 HTML DOM - standard model for HTML documents

Input and output in Javascript


Working with any dynamic language requires the ability to read, process
and output user data. JavaScript is especially useful when you want to
take user information and process it without sending the data back to the
server. JavaScript is much faster than sending everything to the server to
process, but you must be able to read user input and use the right syntax
to work with that input. This article will focus on retrieving user input and
displaying it on the screen through HTML elements or prompts.
Hina Gojwari
CASET College

Displaying Prompts and Retrieving User Responses

JavaScript has a few window object methods that you can use to interact
with your users. The prompt() method lets you open a client-side window
and take input from a user. For instance, maybe you want the user to
enter a first and last name. Normally, you can use an HTML form for user
input, but you might need to get the information before sending the form
back to your server for processing. You can use the window.prompt()
method for small amounts of information. It's not meant for large blocks
of text, but it's useful when you need information before the user
continues to another page.

The following code is an example of the window.prompt method.

var customerName = prompt("Please enter your name", "<name goes


here>");

if (customerName!= null) {

document.getElementById("welcome").innerHTML =

"Hello " + customerName + "! How are you today?";

The first line of code uses the prompt method. Notice that we don't need
the "window" object since JavaScript inherits the main DOM methods and
understands that this is an internal method. The first parameter in the
prompt is what you want to show the user. In this example, we want the
user to enter a name, so the prompt displays "Please enter your name."
The second parameter is the default text. This default text helps the user
understand where to type the name, but if he clicks "OK" without entering
a name, the "<name goes here>" text will be used for the username. You
can create checks in your JavaScript code that detects when the user
doesn't enter a name and just clicks OK, but this code assumes any text
entered is the user's name.

Notice the "if" statement that checks if the "customerName" variable is


null. This logic checks to make sure that the user entered something. It
Hina Gojwari
CASET College

only checks that some character was entered, so the user can type
anything to bypass the "if" statement. The code within the "if" statement
then displays the message to the user in the "welcome" div. We've
covered reading and writing text to a web page, and this is another
example of writing text to the inner HTML section of a div. Remember
that the innerHTML property writes any tags or text within the opening
and closing div tag.

Use this method to get a short string response from your users before
they access a page or before they move on to another page in your site
structure.

The JavaScript Confirmation Message Box

The window.prompt method is one way to read user input, but JavaScript
also provides a way to get confirmation from the user. For instance, you
might want to confirm that the user has entered the right information and
wants to continue with payment. The confirmation window displays the
amount the user will be charged, and the user has the option to confirm
or cancel. You could write a complex JavaScript function to create a new
window for confirmation or you can use the internal window.confirm
method. This method returns either a boolean true result if the user clicks
"OK" or the boolean false result if the user clicks "Cancel." This prompt is
a quick way to get confirmation without using any complex coding logic.

Look at the following JavaScript code.

var r = confirm("Are you sure you want to send a payment?");

if (r == true) {

x = "Payment sent!";

} else {

x = "Payment cancelled!";

}
Hina Gojwari
CASET College

alert (x);

The main utility in the above code is the "confirm" function. This is an
internal JavaScript function from the window object. In other words, using
"window.confirm()" and "confirm" results in the same function. JavaScript
handles the inheritance for you, so you don't need to remember to use
the window object. The confirmation window is also pre-built and shown
to the user. In this example, a prompt displays with the text "Are you
sure you want to send a payment?" The only options for the user are to
click the Cancel button or the OK button. OK is the confirmation that
returns "true." If the user clicks "OK," the variable x contains the text
"Payment sent!" Conversely, if the user clicks the "Cancel" button, x
contains the text "Payment cancelled!" The text is then displayed to the
user using the "alert" function. This is the first time we've seen the alert
function, which is also a part of the window object. Typing "alert" and
"window.alert" results in the same method call. The alert prompt is
common during debugging and development of a web application,
because it's a quick way to check your logic and see the control flow of
your code. The alert function in this example checks that the confirm
window is responding with the right result and the x variable contains the
right text.

Displaying Text from User Input

There are three main HTML tags used to display text after you prompt
users. You've seen two internal JavaScript functions that get user input,
but how do you display it back to the user? The three tags used are the
div, span and text tags. The third one, the text tag, is a form field used to
take string input from the user. You usually use this tag to get input such
as a name or an address, but you can also display input from the user.

The span and div tags are a way to just display the information you've
read in JavaScript prompt windows. You can also display data you've
retrieved from a database.

Let's use the previous example where we prompted the user to enter a
name. We then use the input to display output in a div element. We've
Hina Gojwari
CASET College

seen this before, but this is the first time we've used input directly from
the user.

<!DOCTYPE html>
<html>

<head>

<script>

var customerName = prompt("Please enter your name", "");


if (customerName!= null) {
document.getElementById("welcome").innerHTML =
"Hello " + customerName + "! How are you today?";
}

</script>

</head>

<body>

<div id="welcome">My First JavaScript code.</div>

</body>
</html>

We've included the HTML this time to show you how JavaScript prompts
work with HTML elements. The element we're using is the div HTML tag
with the id of "welcome." The JavaScript prompt asks the user for his
name and then displays the result in the "welcome" div. You can also use
this same code to display the result in the span element using the same
code except change the div tag to a span opening and closing tag.

You've seen the innerHTML property several times, which controls the text
within the opening and closing div or span tags, but what if you want to
use the input to pre-populate a form field? The input text field lets users
input string values, but you can use the methods we've seen to pre-
populate string values automatically. Using the same input example as we
Hina Gojwari
CASET College

previously used, the following code uses the input prompt to enter the
user's name in the "username" text field.

<!DOCTYPE html>
<html>

<head>

<script>

var customerName = prompt("Please enter your name", "");


if (customerName!= null) {
document.getElementById("username").value = customerName;
}

</script>

</head>

<body>

JavaScript Display Possibilities


JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
Hina Gojwari
CASET College

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

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

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

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Changing the innerHTML property of an HTML element is a common way to


display data in HTML.

Using document.write()
For testing purposes, it is convenient to use document.write():

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

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Using document.write() after an HTML document is loaded, will delete all


existing HTML:
Hina Gojwari
CASET College

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

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

The document.write() method should only be used for testing.

Using window.alert()
You can use an alert box to display data:

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

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

You can skip the window keyword.

In JavaScript, the window object is the global scope object. This means that
variables, properties, and methods by default belong to the window object.
This also means that specifying the window keyword is optional:

Example
<!DOCTYPE html>
<html>
<body>
Hina Gojwari
CASET College

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html>

Using console.log()
For debugging purposes, you can call the console.log() method in the browser
to display data.

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

<script>
console.log(5 + 6);
</script>

</body>
</html>

JavaScript Print
JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the
browser to print the content of the current window.

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

<button onclick="window.print()">Print this page</button>

</body>
</html>
Hina Gojwari
CASET College

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>

O/P
Hina Gojwari
CASET College

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

In the next example, the code changes the content of its own element
(using this.innerHTML):

Example
<button onclick="this.innerHTML = Date()">The time is?</button>

O/P

Common HTML Events


Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element


Hina Gojwari
CASET College

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

JavaScript Event Handlers


Event handlers can be used to handle and verify user input, user actions, and
browser actions:

 Things that should be done every time a page loads


 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data
 And more ...

Many different methods can be used to let JavaScript work with events:

 HTML event attributes can execute JavaScript code directly


 HTML event attributes can call JavaScript functions
 You can assign your own event handler functions to HTML elements
 You can prevent events from being sent or being handled
 And more ...

###################### End Of Unit IV #############################

“Web design is not just about creating pretty layouts. It's about
understanding the marketing challenge behind your business.”
ALL THE BEST !!

You might also like