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

JS Students'

JavaScript is a scripting language used to make web pages interactive. It allows dynamic updating of web page content through event handlers and can validate user input. JavaScript code is embedded in HTML and is run in web browsers. It is an interpreted language that is loosely typed, object-based but not fully object-oriented.

Uploaded by

khyati bhutani
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

JS Students'

JavaScript is a scripting language used to make web pages interactive. It allows dynamic updating of web page content through event handlers and can validate user input. JavaScript code is embedded in HTML and is run in web browsers. It is an interpreted language that is loosely typed, object-based but not fully object-oriented.

Uploaded by

khyati bhutani
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 58

JavaScript

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


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”/>
VARIABLE

• Named memory location


VARIABLE

• Named memory location


RAM/Primary Memory
Identifiers – name given to a memory location
Declaration – var variable_name;
Assignment – variable_name = “value”;
Initialisation – var variable_name = “value”;
Puma Nike Reebok
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
var number = 10;
var institute=“sicsr”;
var 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 2020 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 index in arrayName)


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

• sort()

• reverse()

• join([separator]) – default : ,

• push(item1, item2, …, itemN)

• pop()

• 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) - timestamp
DOCUMENT OBJECT MODEL (DOM)
It defines the logical structure of documents and the way a
document is accessed and manipulated.
window

Ba
ck
navigator screen document history
an location
(read-only)
Ve (read-only) d
rsi For
on wa
, form/object rd
Na Co bu
me nte tto
, nt ns
Plu object Are
g- a
ins (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”
DOM

Accept the names of 6 images from the user through text


boxes. When the user clicks on Load Images button, display
the images, along with the image name in ascending order of
names in a 2 x 3 grid (use <TABLE>).

Load Images

Image
Image 1
Name Image
Image 2
Name Image
Image 3
Name
form object

• Point to the form object

1. document.getElementById(‘formId’)
2. document.getElementsByTagName(‘form’)[0]
3. document.forms[0]
OR
document.forms[‘formName’]
OR
document.formName
form object

E.g.
<div id=“header”>
<form>
<input type=“text”>
</form>
<form>
<input type=“button”>
</form>
</div>

var oHeader = document.getElementById(‘header’);


var aForms = oHeader.getElementsByTagName(‘form’);
var oForm = aForms[1];
form object

DOM hierarchy for form object


form properties

1. action
var url = formObject.action;

To Change :
formObject.action = “http://www.mysite.com/intro.html”

2. elements[]

3. length – no. of elements in the form


form properties

Create a form with fields name, age, city, specialization. Display a


button “Fill with Default Values” and a “Submit” button. When
“Fill with Default Values” button is clicked, fill each field in the
form with default values from an array. When “Submit” is
clicked, display the values entered by the user along with the
name of the element in a span tag.
HINT : Loop through the elements in the form and implement
the specified features only for those elements whose type is
text.
Default values can be stored in an array.
E.g. defaultValues = [“Jane Doe”, 19, “Pune”]
Check if formObject.elements[i].type == “text”
FormObject.elements[i].value = defaultValues[i]
form methods

1. submit()

2. reset()
Form Controls

2 ways of accessing:
- getElementById()
- document.formName.controlId
- document.formName.controlName

E.g. <form id=“frm” name=“searchform”>


<input type=“text” name=“uname” id=“uid”>
</form>

document.getElementById(‘uid’)
document.searchform.uid OR document.searchform.uname
document.searchform.elements[0]
document.forms[‘frm’ OR ‘searchform’].elements[‘uid’ OR
‘uname’]
document.forms[‘frm’ OR ‘searchform’].uid OR uname
Form Controls

text, textarea, password


Properties : defaultValue, disabled, name, type, value, size,
readOnly, maxLength
Method : select()
Attributes: selectionStart, selectionEnd
button
Properties : disabled, name, value, type
Method : onClick()

radio, checkbox – same name


Properties : checked, disabled, name, type, value,
defaultChecked – returns the default value checked

select
Properties : disabled, length(no. of options), name, size(no. of
visible contents), selectedIndex, selectedOptions, value

You might also like