You are on page 1of 47

CLIENT-SIDE SCRIPTING LANGUAGE

• Scripting language

• Dynamically generated web pages


JAVASCRIPT
• Is an interpreted scripting language

• JavaScript code is usually embedded directly into HTML pages

• JavaScript is loosely typed, object based but NOT object oriented

• JavaScript can put dynamic text into an HTML page

• JavaScript can be used to validate input data

• JavaScript can be used to detect the visitor’s browser


EVENT HANDLERS

• Special methods associated with objects

• Called when an event occurs

• E.g.
onClick, onMouseDown, onMouseUp, onFocus, onKeyPress, onLoad,
onUnload, onSubmit
JAVASCRIPT

• Accept input

• Process data, e.g. make decisions

• Display messages on the window or status bar

• Change the appearance of the page dynamically

• Create new windows, or close already existing windows

• CANNOT access the file system


USE JAVASCRIPT

• script tag
<html>
<head>
<script type="text/javascript">
//script here
</script>
</head>
</html>

• Referencing external JavaScript file


<script type="text/javascript"
src="directory/MyScript.js>
</script>
JAVASCRIPT & BROWSERS

• Old Browsers
<html>
<head>
<script type="text/javascript">
<!--
script here
-->
</script>
</head>
</html>
JAVASCRIPT & BROWSERS

• <noscript>
<html>
<head>
<script type="text/javascript">
<!--
script here
-->
</script>
</head>
<body>
<noscript>
<p>Browser could not render javascript
</p>
</noscript>
</body>
</html>
FIRST SCRIPT

• Script to display Hello World on the browser


<html>
<head>
<script type="text/javascript">
<!--
document.write("Hello World");
document.write("<h1>Using h1</h1>");
-->
</script>
</head>
</html>
THINGS TO BE KEPT IN MIND

• Quote should end with a matching quote


• Bracket should end with a matching bracket
• It’s a good practice to use semicolon at the end of each
statement
• Indent your code
JAVASCRIPT COMMENTS

• Single line comments - //


• Multi-line comments - /* */

• Write a script to display your name on the browser, in


bold and italics. Give appropriate comments.
OTHER MEANS OF DISPLAYING TEXT :
POPUP BOXES

• Alert Box – OK Button


alert(“Welcome to SICSR!”);

• Confirm Box – OK and Cancel Buttons


confirm(“Are you sure you want to quit?”);

• Prompt Box – Text Box, OK and Cancel Buttons


prompt(“Enter your name”,”admin”);

• <input type=“button” onClick=“confirm(‘Are you sure?’)”


value=“Click Here”/>
FUNCTIONS

• function function_name()
{
//code here
}

function_name()

<input type=“button” onClick=“function_name()”


value=“Click Here”/>
RULES FOR NAMING A VARIABLE

• Variable names must begin with a letter, $ or _

• Variable names can only contain letters, numbers, $ and


underscores(_), they cannot contain special characters

• Variable names are case sensitive (y and Y are different


variables)

• Do not use reserved words/keywords as variable names


VARIABLES

• Declaration
var number;
var no1, no2, name;

• Initialization
number = 10;
institute=“sicsr”;
marks = number + 10.2

• Create two variables called “name” and “age”, and


assign values to them. Display the variables’ values on
the browser.
DATATYPES AND LITERALS

• String – series of characters inside quotes


var name=“jane”;

• Number – any number without quotes


var no = 10.2
var no = 0

• Boolean – true or false

• null

• Array, and Object


FUNCTIONS AND VARIABLE SCOPE

• Scope

• Local Scope – within the function

• Global Scope – declared outside the function


STRING BASICS

• Concatenation operator : +

• Escape Sequence Character - \, for inserting special


characters(“,’,&,;)
DATATYPE CONVERSIONS

• 10+10

• 10+”10”

• 10+”10”+10

• 10+10+”10”

• 10+10+parseInt(”10”)

• 10+10+parseFloat (”10.2”)
• number to string : “”+10
WRITE SCRIPTS FOR THE FOLLOWING

• Accept user’s name and age. Display the same on the


browser.

• Accept a number from the user, add 5 to it and display


in an alert box.

• Create a confirm box and display the return value.


OPERATORS

• Arithmetic operators : +,-,*,/,%,++,--


• Assignment operators : =,+=,-=,*=,/=,%=
• Comparison operators : ==, ===, !=, >, <, >=, <=
• Conditional/Ternary operator : (condition)?true : false
• Logical operators : &&, ||, !
PROGRAMS

• Accept two numbers from the user. Display four buttons on the
screen. The buttons should contain +, -, *, /. Display the result on
the browser, based on the button clicked.
(Hint: Create four functions, and call the corresponding function on
the click event of each button)
• Accept two strings from the user. Check whether both the strings
are equal and display appropriate message using alert.

• Accept two numbers from the user. Using ternary operator, display
the greater of the two numbers on the browser.

• Accept a colour from the user. Accept a text from the user. Display
the text in the colour specified by the user.
CONDITIONAL STATEMENTS

• Used to perform different actions based on different


conditions

• SYNTAX :
if(condition)
{
//statements to execute if condition is true
}
else
{
//statements to execute if condition is false
}
CONDITIONAL STATEMENTS

• SYNTAX :
if(condition 1)
{
//statements to execute if condition1 is true
}
else if(condition 2)
{
//statements to execute if condition2 is true
}
else if(condition n)
{
//statements to execute if condition n is true
}
else
{
//statements to execute if none of the conditions are true
}
CONDITIONAL STATEMENTS

• switch…case – performs an action based on different conditions


SYNTAX:
switch(expression)
{
case value1:
statements
break;
case value2:
statements
break;
………………..
case valueN:
statements
break;
default:
statements
}
FUNCTIONS

• Passing arguments

• Returning values
FUNCTIONS

• Accept a shape from the user. User can enter three shapes :
Circle, Rectangle, Square.
Also ask the user whether he wants to calculate the area or
the perimeter. User can enter “area”, or “perimeter”.
Pass both the user-entered values to a user defined function.

If user entered “circle”, accept the radius.


If user entered “rectangle”, accept the length and the breadth.
If user entered “square”, accept the length.
Based on the second argument passed, calculate and return
the area or the perimeter.

Display the result on the browser.


LOOPS

• while(condition)
{
//statements to be executed
}

• do
{
//statements to be executed
}while(condition);
• for(initialization; condition; increment/decrement)
{
//statements to be executed
}
LOOPS

• For loop variations


for( i=0; i<10; i++);
var i = 0;
for( ; i<10; i++) { }

for(i=0; ; i++) { }

for(i=0; i<10; ) { }
for( ; ; ) { }
for(i=0,j=10; i<10 && j>5; i++,j--)
{ //statements to be executed }
LOOPS
• Display:
* ***** 1 1
** **** 2 2 1 2
*** *** 3 3 3 1 2 3
**** ** 4 4 4 4 1 2 3 4
***** * 5 5 5 5 5 1 2 3 4 5
• Display all the leap years between 1900 and 2012 in the form of a
table with 4 columns. (Divisible by 400 or (divisible by 4 and not
divisible by 100))
• Display:
2
24
246
2468
2 4 6 8 10
LOOPS

• Accept 2 nos. from the user. Display the result of the first
number raised to the second number. Use any loop.

• Accept 2 numbers from the user.


Suppose user enters 2 and 7. The output should be:
2 x 1 = 2 2 x 2 = 4 …………………………… 2 x 10 = 20
3 x 1 = 3 3 x 2 = 6 …………………………… 3 x 10 = 30
.
.
.
.
7 x 1 = 7 7 x 2 = 14 ………………………….. 7 x 10 = 70
LOOPING AND NUMBERS

• Number of digits

• Reverse
RECURSIVE FUNCTIONS

• function x()
{
document.write(“inside function”);
x();
}

• E.g. Calculation of factorial of a number


ARRAYS

• What is an array?
• Creating an array

var subjects = new Array(“JavaScript”, ”C”, “NE”);


document.write(subjects [0]);

var subjects = new Array();


subjects[0] = “JavaScript”;
subjects[1] = “C”;
subjects[2] = “NE”;

var subjects = [“JavaScript”,”C”,”NE”];


ARRAYS

• Looping through an array

for(var value in arrayName)


{
alert(arrayName[value]);
}
for(i=0; i<arrayName.length; i++)
{
alert(arrayName[i]);
}
ARRAY METHODS

• sort()

• reverse()

• join([separator]) – default : ,

• push(item1, item2, …, itemN)

• pop(), unshift(), shift()

• concat(array1, array2)

• slice(start, end) – end argument not included


var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myBest = fruits.slice(-3,-1);
ARRAY METHODS

• toString() – converts the array into a String


ARRAYS

• Multi-dimensional Arrays

var x=[1,2,3,4,5,6];
var y=[x,”bba(it)”,”bca”];

document.write(y[0][1]]);
PROGRAMS

• Write a script to accept numbers from the user till the user
enters a negative number. When the user enters a negative
number, display the average of all the numbers entered,
excluding the negative number.

• Write a script to accept numbers from the user till the user
enters an odd number. When the user enters an odd number,
display the number of dozens that each number
represents(Do not include numbers not divisible by 12).

• Write a script to accept names of mobiles from the user.


Store the names in an array. Display the names in sorted
descending order, separated by a line break. Use join().
PROGRAMS

• Write a script to accept negative numbers from the user till


the user enters 0 or a positive number. Store the numbers in
an array. Using a loop, display the minimum and the maximum
elements in the array. Do not use sort().

• Implement Bubble Sort Algorithm. Accept 10 elements and


store in an array. Display the output on the browser.
String functions

var str = “SICSR is located in Model Colony, Pune”;


str.length
str.indexOf(“in”)
str.lastIndexOf(“o”);
str.search(“in”); //supports regular expressions
str.slice(3, 10);
str.slice(-3, -1);
str.slice(10);
str.substring(10, 15); //no negative indices
str.substr(10, 5); //second parameter indicates the length
str.replace(“SICSR”, “SIG”);
str.toUpperCase();
str.toLowercase();
str.concat(“, Maharashtra”);
str.charAt(0);
String functions

var str = “SICSR is located in Model Colony, Pune”;


str.split(“,”);
str.split(“”);
Math functions

Math.random() - between 0 and 1

Math.min()

Math.max()

Math.round()

Math.ceil()

Math.floor()

Math.floor(Math.random() * 5)
Math functions

Math.abs()

Math.sqrt()

Math.pow(base, exponent)

Math.sin()

Math.cos()

Math.tan()

Math.PI
Date functions

var todaysDate = new Date();


d.toDateString();
d.getDate(); (1-31)
d.getDay(); (0-6)
d.getFullYear()
d.getMonth (0-11)
d.getHours() (0-23)
d.getMinutes (0-59)
d.getSeconds (0-59)
d.getMilliseconds (0-999)
d.getTime() (since epoch – Jan 1, 1970)

new Date(year, month, day, hours, minutes, seconds,


milliseconds)
DOCUMENT OBJECT MODEL (DOM)
It defines the logical structure of documents and the way a
document is accessed and manipulated.
window

navigator screen document history location


(read-only) (read-only)
Back and Forward
buttons
Version, form/object
Name,
Plug-ins
Content Area
object
(property, method, value)
DOM

• Referencing an object

- window.document.getElementById(“elementID”);
- window.document.getElementsByName(“elementName”)[i];

- document.getElementsByName(“nameInput”)[i].value

- document.getElementById(“nameId”).name

- var frm = document.getElementById(“form1”);

- var frm = document.forms[0];

- document.getElementById(“id”).property=“value”
document.getElementById(“para”).innerHTML=“Paragraph”

You might also like