KEMBAR78
JAVA Script | PDF | Java Script | Html
0% found this document useful (0 votes)
15 views27 pages

JAVA Script

JavaScript is a lightweight, object-based scripting language used primarily for creating interactive websites. It allows for client-side validation, dynamic content, and manipulation of HTML and CSS through various methods and functions. Key concepts include variables, operators, functions, and event handling, with syntax rules similar to other programming languages.

Uploaded by

mikey2132468
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)
15 views27 pages

JAVA Script

JavaScript is a lightweight, object-based scripting language used primarily for creating interactive websites. It allows for client-side validation, dynamic content, and manipulation of HTML and CSS through various methods and functions. Key concepts include variables, operators, functions, and event handling, with syntax rules similar to other programming languages.

Uploaded by

mikey2132468
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/ 27

JAVA Script

3.1 Introduction to Java Script:


JavaScript is an object-based scripting language which is lightweight and cross-platform. JavaScript is not a compiled
language, but it is a translated language. The JavaScript Translator (embedded in the browser) is responsible for
translating the JavaScript code for the web browser.

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog
box),
 Displaying clocks etc.
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>

JavaScript Can Change HTML Content:


One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo") and changes the element content
(innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
JavaScript accepts both double and single quotes:
Example
document.getElementById('demo').innerHTML = 'Hello JavaScript';

JavaScript Can Change HTML Styles (CSS)


Changing the style of an HTML element, is a variant of changing an HTML attribute:
Example:

<html> <button type="button"


<body> onclick="document.getElementById('demo').style.fontSi
<h2>What Can JavaScript Do?</h2> ze='35px'">Click Me!</button>
<p id="demo">JavaScript can change the style of an </body>
HTML element.</p> </html>

The <script> Tag


In HTML, JavaScript code must be inserted between <script> and </script> tags.

Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed when "called" for. For example, a function can
be called when an event occurs, like when the user clicks a button.

JavaScript in <head> or <body>


You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example

<!DOCTYPE html> </script>


<html> </head>
<head> <body>
<script> <h1>A Web Page</h1>
function myFunction() { <p id="demo">A Paragraph</p>
document.getElementById("demo").innerHTML = <button type="button" onclick="myFunction()">Try
"Paragraph changed."; it</button>
} </body>
</html>
JavaScript Output:
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().

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:
Example
<!DOCTYPE html> document.getElementById("demo").innerHTML = 5 + 6;
<html> </script></body>
<body> </html>
<h1>My First Web Page</h1> Output: My First Web Page
<p>My First Paragraph</p> My First Paragraph.
<p id="demo"></p> 11
<script>

Using document.write():
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html> <script>
<html> document.write(5 + 6);
<body> </script>
<h1>My First Web Page</h1> </body>
<p>My first paragraph.</p> </html>
Output: My First Web Page
My first paragraph.
Never call document.write after the document has finished loading. It will overwrite the whole document.
11

Using window.alert():
You can use an alert box to display data:
Example
<!DOCTYPE html> window.alert(5 + 6);
<html> </script>
<body> </body>
<h1>My First Web Page</h1> </html>
<p>My first paragraph.</p>
<script>

3.2 Identifier & operator, control structure, functions:

JavaScript Statements
JavaScript statements are composed of:Values, Operators, Expressions, Keywords, and Comments

Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
<html> a = 1;
<body> b = 2;
<h2>JavaScript Statements</h2> c = a + b;
<p>JavaScript statements are separated by document.getElementById("demo1").innerHTML = c;
semicolons.</p> </script>
<p id="demo1"></p> </body>
<script> </html>
var a, b, c;
Output:
JavaScript Statements
JavaScript statements are separated by semicolons.
3

JavaScript Keywords:

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

Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
For Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
Var Declares a variable

JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.

JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
<html> </script>
<body> </body>
<h2>JavaScript Numbers</h2> </html>
<p>Number can be written with or without Output:
decimals.</p> JavaScript Numbers
<p id="demo"></p> Number can be written with or without decimals.
<script> 10.5
document.getElementById("demo").innerHTML = 10.50;

Strings are text, written within double or single quotes:

"John Doe"
'John Doe'
<html> document.getElementById("demo").innerHTML = 'John
<body> Doe';
<h2>JavaScript Strings</h2> </script>
<p>Strings can be written with double or single </body>
quotes.</p> </html>
<p id="demo"></p>
<script>

JavaScript Variables:
In a programming language, variables are used to store data values.JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.
<html> var x;
<body> x = 6;
<h2>JavaScript Variables</h2> document.getElementById("demo").innerHTML = x;
<p>In this example, x is defined as a variable. </script>
Then, x is assigned the value of 6:</p> </body>
<p id="demo"></p> </html>
<script>

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
<html> <script>
<body> document.getElementById("demo").innerHTML = (5 + 6)
<h2>JavaScript Operators</h2> * 10;
<p>JavaScript uses arithmetic operators to compute </script>
values (just like algebra).</p> </body>
<p id="demo"></p> </html>

JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value. The computation is called
an evaluation. For example, 5 * 10 evaluates to 50:
<html> <script>
<body> document.getElementById("demo").innerHTML = 5 *
<h2>JavaScript Expressions</h2> 10;
<p>Expressions compute to values.</p> </script>
<p id="demo"></p> </body></html>
JavaScript Keywords:
JavaScript keywords are used to identify actions to be performed.The var keyword tells the browser to create variables:
<html> y = x * 10;
<body> document.getElementById("demo").innerHTML = y;
<h2>The var Keyword Creates Variables</h2> </script>
<p id="demo"></p>
<script> </body>
var x, y; </html>
x = 5 + 6;

JavaScript Comments:
Not all JavaScript statements are "executed". Code after double slashes // or between /* and */ is treated as a
comment.Comments are ignored, and will not be executed:
var x = 5; // I will be executed
// var x = 6; I will NOT be executed

JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive. The variables lastName and lastname, are two different variables.
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
JavaScript does not interpret VAR or Var as the keyword var.

JavaScript and Camel Case


Historically, programmers have used different ways of joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.

JavaScript Data Types:


JavaScript variables can hold numbers like 100 and text values like "John Doe". In programming, text values are called
text strings. JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
<html> var person = "John Doe";
<body> var answer = 'Yes I am!';

<h2>JavaScript Variables</h2> document.getElementById("demo").innerHTML =


<p>Strings are written with quotes.</p> pi + "<br>" + person + "<br>" + answer;
<p>Numbers are written without quotes.</p> </script>
</body>
<p id="demo"></p> </html>
<script>
var pi = 3.14;

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";
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":

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

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
You can declare many variables in one statement. Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200; A declaration can span multiple lines:
var person = "John Doe",
carName = "Volvo",
price = 200;

Value = undefined
In computer programs, variables are often declared without a value. The value can be something that has to be
calculated, or something that will be provided later, like user input. A variable declared without a value will have the
value undefined.The variable carName will have the value undefined after the execution of this statement:
Example
var carName;

Re-Declaring JavaScript Variables


If you re-declare a JavaScript variable, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
Example
var carName = "Volvo";
var carName;
JavaScript Operators
Assignment
var x = 10;
The addition operator (+) adds numbers:
Adding
var x = 5;
var y = 2;
var z = x + y;
The multiplication operator (*) multiplies numbers.
Multiplying
var x = 5;
var y = 2;
var z = x * y;

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement

JavaScript Functions:
<html> return p1 * p2;
<body> }
<h2>JavaScript Functions</h2> document.getElementById("demo").innerHTML =
<p>This example calls a function which performs a myFunction(4, 3);
calculation, and returns the result:</p> </script>
<p id="demo"></p> </body>
<script> </html>
function myFunction(p1, p2) {

JavaScript Function Syntax:


A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function
names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include
parameter names separated by commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


code to be executed
}
Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values
received by the function when it is invoked.Inside the function, the arguments (the parameters) behave as local
variables.A Function is much the same as a Procedure or a Subroutine, in other programming languages.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

Function Return
When JavaScript reaches a return statement, the function will stop executing.If the function was invoked from a
statement, JavaScript will "return" to execute the code after the invoking statement.Functions often compute a return
value. The return value is "returned" back to the "caller"
<html> document.getElementById("demo").innerHTML = x;
<body>
<h2>JavaScript Functions</h2> function myFunction(a, b) {
<p>This example calls a function which performs a return a * b;
calculation and returns the result:</p> }
<p id="demo"></p> </script>
<script> </body>
var x = myFunction(4, 3); </html>

The () Operator Invokes the Function


Accessing a function without () will return the function definition instead of the function result:
<html> return (5/9) * (f-32);
<body> }
<h2>JavaScript Functions</h2> document.getElementById("demo").innerHTML =
<p>Accessing a function without () will return the toCelsius;
function definition instead of the function result:</p> </script>
<p id="demo"></p> </body>
<script> </html>
function toCelsius(f) {

Functions Used as Variable Values


Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.
<html>
<body> function toCelsius(fahrenheit) {
<h2>JavaScript Functions</h2> return (5/9) * (fahrenheit-32);
<p id="demo"></p> }
<script> </script>
document.getElementById("demo").innerHTML = </body>
"The temperature is " + toCelsius(77) + " Celsius"; </html>
3.3 Document object model(DOM),

Browser Object Model:


1. Browser Object Model (BOM)
The Browser Object Model (BOM) is used to interact with the browser.The default object of browser is window means
you can call all the functions of window by specifying window or directly. For example:
1. window.alert("hello ");
is same as:
1. alert("hello");
You can use a lot of properties (other objects) defined underneath the window object like document, history, screen,
navigator, location, innerHeight, innerWidth,
Note: The document object represents an html document. It forms DOM (Document Object Model).

Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object
The window object represents a window in browser. An object of window is created automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript objects are string, array, date etc.
Note: if html document contains frame or iframe, browser creates additional window objects for each frame.
Methods of window object
The important methods of window object are as follows:
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating expressions etc.
Example of alert() in javascript
It displays alert dialog box. It has message and ok button.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

Example of confirm() in javascript


It displays the confirm dialog box. It has message with ok and cancel buttons.
1. <script type="text/javascript"> 9. }
2. function msg(){ 10.
3. var v= confirm("Are u sure?"); 11. }
4. if(v==true){ 12. </script>
5. alert("ok"); 13.
6. } 14. <input type="button" value="delete record" onc
7. else{ lick="msg()"/>
8. alert("cancel");
15.
Example of prompt() in javascript
It displays prompt dialog box for input. It has message and textfield.
1. <script type="text/javascript"> 6. }
2. function msg(){ 7. </script>
3. var v= prompt("Who are you?"); 8.
4. alert("I am "+v); 9. <input type="button" value="click" onclick="ms
5. g()"/>

Example of open() in javascript


It displays the content in a new window.
1. <script type="text/javascript"> 5. </script>
2. function msg(){ 6. <input type="button" value="javatpoint" onclick
3. open("http://www.javatpoint.com"); ="msg()"/>
4. }

Example of setTimeout() in javascript


It performs its task after the given milliseconds.
1. <script type="text/javascript"> 8. }
2. function msg(){ 9. </script>
3. setTimeout( 10.
4. function(){ 11. <input type="button" value="click" onclick="ms
5. alert("Welcome to Javatpoint after 2 seconds") g()"/>
6. },2000);
7.
JavaScript History Object
1. History Object
2. Properties of History Object
3. Methods of History Object
4. Example of History Object
The JavaScript history object represents an array of URLs visited by the user. By using this object, you can load previous,
forward or any particular page. The history object is the window property, so it can be accessed by:
1. window.history
Or,
1. history

Property of JavaScript history object


There are only 1 property of history object.
No. Property Description
1 length returns the length of the history URLs.

Methods of JavaScript history object


There are only 3 methods of history object.
No. Method Description
1 forward() loads the next page.
2 back() loads the previous page.
3 go() loads the given page number.

Example of history object


Let’s see the different usage of history object.
1. history.back();//for previous page
2. history.forward();//for next page
3. history.go(2);//for next 2nd page
4. history.go(-2);//for previous 2nd page
JavaScript Navigator Object:
1. Navigator Object
2. Properties of Navigator Object
3. Methods of Navigator Object
4. Example of Navigator Object
The JavaScript navigator object is used for browser detection. It can be used to get browser information such as
appName, appCodeName, userAgent etc.The navigator object is the window property, so it can be accessed by:
1. window.navigator
Or,
1. navigator

Property of JavaScript navigator object


There are many properties of navigator object that returns information of the browser.
No. Property Description
1 appName returns the name
2 appVersion returns the version
3 appCodeName returns the code name
4 cookieEnabled returns true if cookie is enabled otherwise false
5 userAgent returns the user agent
6 language returns the language. It is supported in Netscape and Firefox only.
7 userLanguage returns the user language. It is supported in IE only.
8 plugins returns the plugins. It is supported in Netscape and Firefox only.
9 systemLanguage returns the system language. It is supported in IE only.
10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.
11 platform returns the platform e.g. Win32.
12 online returns true if browser is online otherwise false.

Methods of JavaScript navigator object


The methods of navigator object are given below.
No. Method Description
1 javaEnabled() checks if java is enabled.
2 taintEnabled() checks if taint is enabled. It is deprecated since JavaScript 1.2.

Example of navigator object


Let’s see the different usage of history object.
1. <script>
2. document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
3. document.writeln("<br/>navigator.appName: "+navigator.appName);
4. document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
5. document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
6. document.writeln("<br/>navigator.language: "+navigator.language);
7. document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
8. document.writeln("<br/>navigator.platform: "+navigator.platform);
9. document.writeln("<br/>navigator.onLine: "+navigator.onLine);
10. </script>
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.
1. window.document
Is same as
1. document
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."

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.
Accessing field value by document object
In this example, we are going to get the value of input text by user. Here, we are using document.form1.name.value to
get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome message.
1. <script type="text/javascript"> 8. <form name="form1">
2. function printvalue(){ 9. Enter Name:<input type="text" name="name"/
3. var name=document.form1.name.value; >
4. alert("Welcome: "+name); 10. <input type="button" onclick="printvalue()" val
5. } ue="print name"/>
6. </script> 11. </form>
7.
12.
Javascript - document.getElementById() method:
1. getElementById() method
2. Example of getElementById()
The document.getElementById() method returns the element of specified id.
we can use document.getElementById() method to get value of the input text. But we need to define id for the input
field.
Let's see the simple example of document.getElementById() method that prints cube of the given number.
1. <script type="text/javascript"> 7. <form>
2. function getcube(){ 8. Enter No:<input type="text" id="number" name
3. var number=document.getElementById("numb ="number"/><br/>
er").value; 9. <input type="button" value="cube" onclick="ge
4. alert(number*number*number); tcube()"/>
5. } 10. </form>
6. </script>
11.
Javascript - document.getElementsByName() method
1. getElementsByName() method
2. Example of getElementsByName()
The document.getElementsByName() method returns all the element of specified name.The syntax of the
getElementsByName() method is given below:
1. document.getElementsByName("name")
Here, name is required.
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using getElementsByName() method to get all
the genders.
1. <script type="text/javascript"> 9. Male:<input type="radio" name="gender" value
2. function totalelements() ="male">
3. { 10. Female:<input type="radio" name="gender" val
4. var allgenders=document.getElementsByName( ue="female">
"gender"); 11.
5. alert("Total Genders:"+allgenders.length); 12. <input type="button" onclick="totalelements()"
6. } value="Total Genders">
7. </script> 13.
8. <form> 14. </form>
Javascript - document.getElementsByTagName() method:
1. getElementsByTagName() method
2. Example of getElementsByTagName()
The document.getElementsByTagName() method returns all the element of specified tag name.
The syntax of the getElementsByTagName() method is given below:
1. document.getElementsByTagName("name")
Here, name is required.
Example of document.getElementsByTagName() method
In this example, we going to count total number of paragraphs used in the document. To do this, we have called the
document.getElementsByTagName("p") method that returns the total paragraphs.
1. <script type="text/javascript"> 8. <p>This is a pragraph</p>
2. function countpara(){ 9. <p>Here we are going to count total number of
3. var totalpara=document.getElementsByTagNam paragraphs by getElementByTagName() method
e("p"); .</p>
4. alert("total p tags are: "+totalpara.length); 10. <p>Let's see the simple example</p>
5. 11. <button onclick="countpara()">count paragraph
6. } </button>
7. </script>

Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the html document.It is used mostly in the web
pages to generate the dynamic html such as registration form, comment form, links etc.

Example of innerHTML property


we are dynamically writing the html form inside the div name having the id mylocation. We are identifing this position
by calling the document.getElementById() method.
1. <script type="text/javascript" > 6. }
2. function showcommentform() { 7. </script>
3. var data="Name:<input type='text' name='nam 8. <form name="myForm">
e'><br>Comment:<br><textarea rows='5' cols=' 9. <input type="button" value="comment" onclick
80'></textarea> ="showcommentform()">
4. <br><input type='submit' value='Post Comment 10. <div id="mylocation"></div>
'>"; 11. </form>
5. document.getElementById('mylocation').innerH
TML=data;

Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html document. Here, text will not be interpreted
as html text but a normal text.It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.

Javascript innerText Example


In this example, we are going to display the password strength when releases the key after press.
1. <script type="text/javascript" > 5. msg="good";
2. function validate() { 6. }
3. var msg; 7. else{
4. if(document.myForm.userPass.value.length>5){ 8. msg="poor";
9. } 14. <form name="myForm">
10. document.getElementById('mylocation').innerT 15. <input type="password" value="" name="userP
ext=msg; ass" onkeyup="validate()">
11. } 16. Strength:<span id="mylocation">no strength</
12. span>
13. </script> 17. </form>

3.5 Predefined functions, math & string functions:

JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)

1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given below:
1. var stringname="string value";
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
Output:
This is string literal

2) By string object (using new keyword)


The syntax of creating string object using new keyword is given below:
1. var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Let’s see the example of creating string in JavaScript by new keyword.
1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>

Output:
hello javascript string
JavaScript String Methods
Let's see the list of JavaScript string methods with examples.
Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
It provides the position of a char value present in the given string by searching a character from
lastIndexOf()
the last position.
It searches a specified regular expression in a given string and returns its position if a match
search()
occurs.
It searches a specified regular expression in a given string and returns that regular expression if a
match()
match occurs.
replace() It replaces a given string with the specified replacement.
It is used to fetch the part of the given string on the basis of the specified starting position and
substr()
length.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
1) JavaScript String charAt(index) Method
The JavaScript String charAt() method returns the character at the given index.
1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Output:
v
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Output:
javascript concat example
3) JavaScript String indexOf(str) Method
The JavaScript String indexOf(str) method returns the index position of the given string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Output:
11
4) JavaScript String lastIndexOf(str) Method
The JavaScript String lastIndexOf(str) method returns the last index position of the given string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>
Output:
16

5) JavaScript String toLowerCase() Method


The JavaScript String toLowerCase() method returns the given string in lowercase letters.
1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>

Output:
javascript tolowercase example

6) JavaScript String toUpperCase() Method


The JavaScript String toUpperCase() method returns the given string in uppercase letters.
1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>

Output:
JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given beginIndex to endIndex.
In slice() method, beginIndex is inclusive and endIndex is exclusive.
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>

Output:
cde

8) JavaScript String trim() Method


The JavaScript String trim() method removes leading and trailing whitespaces from the string.
1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>

Output:
javascript trim

JavaScript Date Object


The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help
of JavaScript date object.You can use different Date constructors to create date object. It provides methods to get and
set day, month, year, hour, minute and seconds.

Constructor
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Date Methods
Let's see the list of JavaScript date methods with their description.
Methods Description
It returns the integer value between 1 and 31 that represents the day for the specified date on the
getDate()
basis of local time.
It returns the integer value between 0 and 6 that represents the day of the week on the basis of local
getDay()
time.
getFullYears() It returns the integer value that represents the year on the basis of local time.
getHours() It returns the integer value between 0 and 23 that represents the hours on the basis of local time.
It returns the integer value between 0 and 999 that represents the milliseconds on the basis of local
getMilliseconds()
time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of local time.
getSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of local time.
setDate() It sets the day value for the specified date on the basis of local time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local time.
setHours() It sets the hour value for the specified date on the basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local time.
setMinutes() It sets the minute value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
setSeconds() It sets the second value for the specified date on the basis of local time.
toString() It returns the date in the form of string.
JavaScript Date Example
Let's see the simple example to print date object. It prints date and time both.
1. Current Date and Time: <span id="txt"></span>
2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>

Output:
Current Date and Time: Tue Oct 23 2018 01:36:29 GMT+0530 (India Standard Time)
Let's see another code to print date/month/year.
1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>
Output:
Date is: 23/10/2018

JavaScript Current Time Example


Let's see the simple example to print current time of system.
1. Current Time: <span id="txt"></span>
2. <script>
3. var today=new Date();
4. var h=today.getHours();
5. var m=today.getMinutes();
6. var s=today.getSeconds();
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
8. </script>

Output:
Current Time: 1:36:29

JavaScript Math
The JavaScript math object provides several constants and methods to perform mathematical operation. Unlike date
object, it doesn't have constructors.
JavaScript Math Methods
Let's see the list of JavaScript Math methods with description.
Methods Description
abs() It returns the absolute value of the given number.
acos() It returns the arccosine of the given number in radians.
asin() It returns the arcsine of the given number in radians.
atan() It returns the arc-tangent of the given number in radians.
cbrt() It returns the cube root of the given number.
ceil() It returns a smallest integer value, greater than or equal to the given number.
cos() It returns the cosine of the given number.
cosh() It returns the hyperbolic cosine of the given number.
exp() It returns the exponential form of the given number.
floor() It returns largest integer value, lower than or equal to the given number.
hypot() It returns square root of sum of the squares of given numbers.
log() It returns natural logarithm of a number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
pow() It returns value of base to the power of exponent.
random() It returns random number between 0 (inclusive) and 1 (exclusive).
round() It returns closest integer value of the given number.
sign() It returns the sign of the given number
sin() It returns the sine of the given number.
sinh() It returns the hyperbolic sine of the given number.
sqrt() It returns the square root of the given number
tan() It returns the tangent of the given number.
tanh() It returns the hyperbolic tangent of the given number.
trunc() It returns an integer part of the given number.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
1. Square Root of 17 is: <span id="p1"></span>
2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>

Output:
Square Root of 17 is: 4.123105625617661

Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.
1. Random Number is: <span id="p2"></span>
2. <script>
3. document.getElementById('p2').innerHTML=Math.random();
4. </script>

Output:
Random Number is: 0.4886444692425461

Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
1. 3 to the power of 4 is: <span id="p3"></span>
2. <script>
3. document.getElementById('p3').innerHTML=Math.pow(3,4);
4. </script>

Output:
3 to the power of 4 is: 81

Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number. For example 3 for 3.7, 5 for 5.9
etc.
1. Floor of 4.6 is: <span id="p4"></span>
2. <script>
3. document.getElementById('p4').innerHTML=Math.floor(4.6);
4. </script>

Output:
Floor of 4.6 is: 4

Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For example 4 for 3.7, 6 for 5.9 etc.
1. Ceil of 4.6 is: <span id="p5"></span>
2. <script>
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);
4. </script>

Output:
Ceil of 4.6 is: 5

Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the given number. If fractional part is
equal or greater than 0.5, it goes to upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
1. Round of 4.3 is: <span id="p6"></span><br>
2. Round of 4.7 is: <span id="p7"></span>
3. <script>
4. document.getElementById('p6').innerHTML=Math.round(4.3);
5. document.getElementById('p7').innerHTML=Math.round(4.7);
6. </script>

Output:
Round of 4.3 is: 4
Round of 4.7 is: 5

Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For example 4 for -4, 6.6 for -6.6
etc.
1. Absolute value of -4 is: <span id="p8"></span>
2. <script>
3. document.getElementById('p8').innerHTML=Math.abs(-4);
4. </script>

Output:
Absolute value of -4 is: 4

JavaScript Number Object


The JavaScript number object enables you to represent a numeric value. It may be integer or floating-point. JavaScript
number object follows IEEE standard to represent the floating-point numbers.
By the help of Number() constructor, you can create number object in JavaScript. For example:
1. var n=new Number(value);
If value can't be converted to number, it returns NaN(Not a Number) that can be checked by isNaN() method.
You can direct assign a number to a variable also. For example:
1. var x=102;//integer value
2. var y=102.7;//floating point value
3. var z=13e4;//exponent value, output: 130000
4. var n=new Number(16);//integer value by number object

Output:
102 102.7 130000 16

JavaScript Number Constants


Let's see the list of JavaScript number constants with description.
Constant Description
MIN_VALUE returns the largest minimum value.
MAX_VALUE returns the largest maximum value.
POSITIVE_INFINITY returns positive infinity, overflow value.
NEGATIVE_INFINITY returns negative infinity, overflow value.
NaN represents "Not a Number" value.

JavaScript Number Methods


Let's see the list of JavaScript number methods with their description.
Methods Description
isFinite() It determines whether the given value is a finite number.
isInteger() It determines whether the given value is an integer.
parseFloat() It converts the given string into a floating point number.
parseInt() It converts the given string into an integer number.
toExponential() It returns the string that represents exponential notation of the given number.
toFixed() It returns the string that represents a number with exact digits after a decimal point.
toPrecision() It returns the string representing a number of specified precision.
toString() It returns the given number in the form of string.

3.6 Array in Java scripts


JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:
1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let’s see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>

The .length property returns the length of an array.


Output of the above example
Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:
1. var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let’s see the example of creating array directly.
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>

Output of the above example


Arun
Varun
John

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value
explicitly.
The example of creating object by array constructor is given below.
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>

Output of the above example


Jai
Vijay
Smith

JavaScript Array Methods


Let's see the list of JavaScript array methods with their description.
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the modified array.
every() It determines whether all the elements of an array are satisfying the provided function conditions.
fill() It fills elements into an array with static values.
filter() It returns the new array containing the elements that pass the provided function conditions.
find() It returns the value of the first element in the given array that satisfies the specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of the first match.
join() It joins the elements of an array as a string.
lastIndexOf() It searches the specified element in the given array and returns the index of the last match.
map() It calls the specified function for every array element and returns the new array
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse() It reverses the elements of given array.
shift() It removes and returns the first element of an array.
slice() It returns a new array containing the copy of the part of the given array.
sort() It returns the element of the given array in a sorted order.
splice() It add/remove elements to/from the given array.
unshift() It adds one or more elements in the beginning of the given array.

3.7 Event handling in Java script:


HTML/DOM events for JavaScript
HTML or DOM events are widely used in JavaScript code. JavaScript code is executed with HTML/DOM events. So before
learning JavaScript, let’s have some idea about events.
Events Description
onclick occurs when element is clicked.
ondblclick occurs when element is double-clicked.
onfocus occurs when an element gets focus such as button, input, textarea etc.
onblur occurs when form looses the focus from an element.
onsubmit occurs when form is submitted.
onmouseover occurs when mouse is moved over an element.
onmouseout occurs when mouse is moved out from an element (after moved over).
onmousedown occurs when mouse button is pressed over an element.
onmouseup occurs when mouse is released from an element (after mouse is pressed).
onload occurs when document, object or frameset is loaded.
onunload occurs when body or frameset is unloaded.
onscroll occurs when document is scrolled.
onresized occurs when document is resized.
onreset occurs when form is reset.
onkeydown occurs when key is being pressed.
onkeypress occurs when user presses the key.
onkeyup occurs when key is released.
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick=JavaScript
Examples of HTML events:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html> text!</h1>
<html>
<body> </body>
</html>
<h1 onclick="this.innerHTML = 'Ooops!'">Click on this
In this example, a function is called from the event handler:
Example
<!DOCTYPE html> function changeText(id) {
<html> id.innerHTML = "Ooops!";
<body> }
</script>
<h1 onclick="changeText(this)">Click on this text!</h1>
</body>
<script> </html>

HTML Event Attributes


To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
<html> document.getElementById("demo").innerHTML =
<body> Date();
}
<p>Click the button to display the date.</p> </script>

<button onclick="displayDate()">The time is?</button> <p id="demo"></p>

<script> </body>
function displayDate() { </html>

Assign Events Using the HTML DOM


The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example
Assign an onclick event to a button element:
<html> document.getElementById("myBtn").onclick =
<body> displayDate;

<p>Click "Try it" to execute the displayDate() function displayDate() {


function.</p> document.getElementById("demo").innerHTML =
Date();
<button id="myBtn">Try it</button> }
</script>
<p id="demo"></p>
</body>
<script> </html>

The onload and onunload Events


The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of
the web page based on the information.
The onload and onunload events can be used to deal with cookies.

<html> } else {
<body onload="checkCookies()"> text = "Cookies are not enabled.";
}
<p id="demo"></p> document.getElementById("demo").innerHTML =
text;
<script> }
function checkCookies() { </script>
var text = "";
if (navigator.cookieEnabled == true) { </body>
text = "Cookies are enabled."; </html>
The onchange Event
The onchange event is often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the
content of an input field.
Example
<html>
<head> Enter your name: <input type="text" id="fname"
<script> onchange="myFunction()">
function myFunction() { <p>When you leave the input field, a function is
var x = document.getElementById("fname"); triggered which transforms the input text to upper
x.value = x.value.toUpperCase(); case.</p>
}
</script> </body>
</head> </html>
<body>

The onmouseover and onmouseout Events


The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an
HTML element:
<html> <div onmouseover="mOver(this)"
<body> onmouseout="mOut(this)"
style="background-
color:#D94A38;width:120px;height:20px;padding:40px; function mOut(obj) {
"> obj.innerHTML = "Mouse Over Me"
Mouse Over Me</div> }
</script>
<script>
function mOver(obj) { </body>
obj.innerHTML = "Thank You" </html>
}

The onmousedown, onmouseup and onclick Events


The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked,
the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered,
finally, when the mouse-click is completed, the onclick event is triggered.
<html>
<body>

<div onmousedown="mDown(this)"
onmouseup="mUp(this)"
style="background-
color:#D94A38;width:90px;height:20px;padding:40px;"
>
Click Me</div>

<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}

function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>

</body>
</html>

You might also like