Nothing Special   »   [go: up one dir, main page]

Unit - 2-JS Part 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 43

Unit 2 JS

function functionName([arg1, arg2, ...argN])


{
//code to be executed
}
Example:
<html>
<body>
<script>
function msg()
{
alert("hello! this is message");
}
</script>
<input type="button" value="call function"/>
</body>
</html>
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" ></form>
</body>
</html>
<html>
<head> <body>
<script> <form name=“frm1”>
function chkval() <input type=“text” name=“txtname”>
{ <br>
var uname=document.frm1.txtname.value; <input type=“password” name=“txtpass”>
var upass = document.frm1.txtpass.value; <br>
<input type=“button” >If (uname=“ ”) </form>
{
Alert(“Username cannot be left blank”); </body>
}

If(upass.length<4)
{
Alert(“Please give password more than 4
characters”);
}
}
</script>
</head>
<html> <body>
<head> <form name=“frm1”>
<script> <input type=“text” name=“txtnum”>
function chkval() <br>
{ <input type=“button” >var </form>
num1=parseInt(document.frm1.txtnum.val
ue); </body>
If (num1 % 2 == 0)
{
Alert(“Even Number”);
}
else
{
Alert(“Odd Number”);
}
}
</script>
<html>
Rest Parameter <body>
<script>
The rest parameter is introduced in ECMAScript
function show(...args)
2015 or ES6, which improves the ability to handle
{
parameters.
let sum = 0;
for (let i of args)
The rest parameter allows us to represent an
{
indefinite number of arguments as an array. By
sum += i;
using the rest parameter, a function can be called
}
with any number of arguments.
document.write("Sum = "+sum);
}
The rest parameter is prefixed with three dots (...).
show(10, 20, 30);

</script>
</body>
</html>
JavaScript Global Variable

A JavaScript global variable is declared outside the function or declared with


window object. It can be accessed from any function.
<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
</script>
• Declaring JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window object.
For example:
function m()
{
window.value=100; //declaring global variable by window object
}
function n()
{
alert(window.value); //accessing global variable from other function
}
Declaring variable with var, let and const

var and let are both used for variable declaration in javascript but the difference between
them is that var is function scoped and let is block scoped. Variable declared by let cannot
be redeclared and must be declared before use whereas variables declared with var
keyword are hoisted.

<html>
<body> <html>
<script> <body>
document.write(x); Output <script>
var x =10; undefined 10 document.write(x); Output
document.write(x); let x =10;
</script> document.write(x);
</body> </script>
</html> </body>
</html>
These objects can be put into the following three categories:
•Built-in objects
•HTML objects
•Browser objects (BOM)

Built-in objects include string objects, the Date object, and the Math object.
They are referred to as built-in because they really do not have anything to do
with Web pages, HTML, URLs, the current browser environment, or anything
visual.

HTML objects, in turn, are directly associated with elements of Web pages.
Every link and anchor is a JavaScript object. Every form, and every element
within a form, is an HTML object. The hierarchical organization of display
elements on a Web page is reflected almost exactly in a hierarchical set of
nested HTML objects.
Browser objects are at the top of JavaScript's object hierarchy. These objects
represent large scale elements of the browser's current environment, and
include objects such as window (the current window), history (the list of
previously visited pages), and location (the URL of the current page).
Built-In Objects

1. String Objects
String objects are the most built-in of all the built-in JavaScript objects. You do not even
use new when creating a string object. Any variable whose value is a string is actually a
string object.

String objects have one property, length, and many methods.

<script>
var a = “Hello World”;
alert(a.length);

</script>
The following methods can be used on string objects to access, control, or modify their
content:
1. String.charAt( idx )
2. String.at()
3. String.indexOf( chr )
4. String.lastIndexOf( chr )
5. String.substring( fromidx, toidx )
6. String.toLowerCase()
7. String.toUpperCase()
8. String.concat()
9. String replace()
10. String.split()
charAt()
The charAt() method returns the character at a specified index (position) in a string.

<html>
<body>
<form name="frm">
<input type="text" name="txt1"></p>
<script>
var text = “hello";
var x = text.charAt(0);

document.frm.txt1.value = x.toUpperCase();
</script>

</body>
</html>
charCodeAt
This method returns the Unicode (ASCII) of the character at a given position in a string.

<script>
var a = "Hello World";
alert(a.charCodeAt(0));

</script>
String.at()
The at() method returns the character at a specified index (position) in a string.

<script>
var a = "Hello World";
alert(a.at(4));

</script>
IndexOf

indexOf() returns the position of the first occurrence of a value in a string.

<script>
var a = "Hello World";
alert("The Index value of World is " + a.indexOf("World"));

</script>
lastIndexOf
lastIndexOf() returns the index of the last occurrence of a specified value in a string.

<script>
var a = "Hello World";
alert("The Index value of last occurence of o is " + a.lastIndexOf("o"));

</script>
substring(start, end)
substring() extracts a part of a string. From start to end-1.

<script>
var a = "Hello World";
alert("The substring extracted is " + a.substring(2,4));

</script>
concat()

The concat() method joins two or more strings.

<script>
var a = "Hello";
var b = "World";
alert("The substring extracted is " + a.concat(b));
</script>

<script>
var a = "Web";
var b = "Tech";
var c = "Class"
alert("The substring extracted is " + a.concat(b,c));

</script>
Split()

This function splits a string into an array of substrings, and returns the array.

<script>
var a = "This is a web Tech Class";
alert("The split string is " + a.split(" "));
</script>
replace()

<script>
var a = "This is a web Tech Class";
alert("The new string is " + a.replace("Class", "Session"));
</script>
2. Math object

The Math object has the following methods:

 abs( num )  pow( num1, num2 )


 cos( ang )  random()
 exp( num )  round( num )
 log( num )  sin( ang )
 max( num1, num2 )  sqrt( num )
 max( num1, num2 )  tan( ang)
Number to Integer
Math.round() Math.round(3.6); Output: 4
It returns the nearest integer.

Math.ceil()

Math.ceil() rounds a number up to its nearest integer Math.ceil(4.1); Output: 5

Math.round()

It returns the value of x rounded down to its nearest integer.


Math.floor(4.9); Output: 4
Math.pow()
It returns the value of x to the power of y. Math.pow(8, 2); Output : 64

Math.sqrt()
Math.sqrt(64); Output : 8
It returns the square root of x.

Math.sin()
It returns the sine of the angle x.
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest value in a list of
arguments.

Math.min(0, 150, 30, 20, -8, -200);

Math.random()
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

0 to 0.9 <script>
document.write(Math.trunc(Math.random()*10))
</script>
3. Date Object
The Date object is useful for designing sites that are sensitive to the time of
day, or use time-based information to present to the user new information.
You cannot work with dates prior to 1/1/70.

It differs from the String object in that you use a statement called new to
create it.
Using the new statement, you create a Date object that contains information
down to the millisecond at that instant.
today = new Date(); getDate today.getDate()
getDay yesterday.getDay()
getHours today.getHours()
getMinutes today.getMinutes()
getMonth year.getMonth()
getDate() : It returns the integer value between 1 and 31 to represent the day of the month.

getDay(): It returns the integer value between 0 and 6 to represent the day of the week.

getFullYears(): It returns the year value.

getMonth(): It returns a value between 0 and 11 to represent the month.

getHours(): It returns a value between 0 and 23 to represent hours as per local time.

getMinutes(): It returns a value between 0 and 59 to represent minutes as per local time.
Number Object

IsFinite(): It determines whether the given value is a finite number.

Number.isFinite(x)

IsInteger(): Returns true if the argument is an integer

parseFloat(): Parses its argument and returns a floating-point number.

parseInt(): Parses its argument and returns a whole number.


The Browser Object Model (BOM)
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser rather than
the content of the page.
The Window Object

The window object is supported by all browsers. It represents the browser's window.
We can call all the functions of window by specifying window or directly. For example:

window.alert("hello world");

is same as:

alert("hello world");
Some important methods of window object

Method] Description

alert() displays the alert box containing message with ok button.

displays the confirm dialog box containing message with


confirm()
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.
performs action after specified time like calling function,
setTimeout() evaluating expressions etc.
The setInterval() method repeats a block of code at every
Setinterval() given timing event.
<html> <head>
<script>
function openWin()
{
myWindow=window.open("","","width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin()
{ myWindow.close(); }

</script> </head>
<body>
<input type="button" value="Open 'myWindow'" />
<input type="button" value="Close 'myWindow'" />
</body> </html>
confirm() in javascript
<html>
<head>
<script>
function delmsg(){
var x = confirm("Are u sure want to delete?");
if(x==true){
alert(“Content Deleted");
}
else{
alert(“Action Cancelled by User");
}
}
</script>
</head>
<body>
<input type="button" value="delete " > </body>
</html>
prompt() in javascript

<html>
<head>
<script>
function display(){
var uname = prompt("Enter your name");
document.write("Your Name is" + uname);
}
</script>
</head>
<body>
<input type="button" value="click" > </body>
</html>
setTimeout()

<SCRIPT LANGUAGE=JAVASCRIPT>
<!--
function mySubmit() {
setTimeout('document.myForm.reset()',2000);
return false;
}

//--></SCRIPT>

<FORM NAME="myForm" mySubmit()">


<INPUT TYPE="INPUT">
<INPUT TYPE="SUBMIT">
</FORM>
setInterval() <html>
<body>
The setInterval() method calls a
function or evaluates an <input type="text" id="clock">
expression at specified intervals <script language=javascript>
(in milliseconds).
function clock()
The setInterval() method will {
continue calling the function var d=new Date();
until clearInterval() is called, or var t=d.toLocaleTimeString();
the window is closed. document.getElementById("clock").value=t;
}

setInterval(clock,1000);
</script>
Properties of window object
Object Description

navigator The navigator object provides properties that expose information


about the current browser to JavaScript scripts.
window The window object provides methods and properties for dealing
with the actual Navigator window, including objects for each frame.

location The location object provides properties and methods for working
with the currently open URL.
history The history object provides information about the history list and
enables limited interaction with the list.
document The document object is one of the most heavily used objects in the
hierarchy. It contains objects, properties, and methods for working
with document elements including forms, links, anchors, and with
applets.
JavaScript 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:


• window.history
or,
• history
Methods of JavaScript history object

1 forward() loads the next page.


2 back() loads the previous page.
loads the given page
3 go()
number.

Example of history object

history.back(); //for previous page


history.forward(); //for next page
history.go(2); //for next 2nd page
history.go(-2); //for previous 2nd page
JavaScript Browser object
<html>
<head>
<script type="text/javascript">
function detectBrowser()
{
var browser=navigator.appName;
var b_version=navigator.appVersion;

document.write(browser);
}
</script>
</head>
<body ></body>
</html>
Location Object
The location object describes the URL of a document.

Window.location(“url”);

JavaScript Screen Object

The JavaScript screen object holds information of browser screen. It can be used to
display screen width, height etc.
it can be accessed by:
• window.screen
or,
• screen

You might also like