0% found this document useful (0 votes)
12 views52 pages

02.04. JavaScript-2

The document provides an overview of web programming with a focus on JavaScript, detailing client-side scripting, its pros and cons, and comparisons with server-side scripting. It covers fundamental concepts such as variables, functions, conditions, loops, and the Document Object Model (DOM), along with practical examples of JavaScript usage. Additionally, it explains the creation and manipulation of objects, arrays, and popup boxes in JavaScript.

Uploaded by

boo20012007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views52 pages

02.04. JavaScript-2

The document provides an overview of web programming with a focus on JavaScript, detailing client-side scripting, its pros and cons, and comparisons with server-side scripting. It covers fundamental concepts such as variables, functions, conditions, loops, and the Document Object Model (DOM), along with practical examples of JavaScript usage. Additionally, it explains the creation and manipulation of objects, arrays, and popup boxes in JavaScript.

Uploaded by

boo20012007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Web Programming & Python:

Javascript

Prepared By:
Darsha Chauhan
● Introduction
● Task Performed by Client side Scripts
● Pros & Cons of Client side Scripts
● Client side Scripts V/S Server side Scripts
● Variables
● Functions

Outline ● Conditions & Loops


● Pop up boxes
● External JavaScript
● JavaScript Objects
● DOM
● DHTML
● For a Web page, HTML supplies document content and
structure while CSS provides presentation styling
● In addition, client-side scripts can control browser
Introduction actions associated with a Web page.
● Client-side scripts are almost written in the Javascript
language to control browser’s actions.
● Client-side scripting can make Web pages more
dynamic and more responsive
● Checking correctness of user input
● Monitoring user events and specifying reactions

Task ● Replacing and updating parts of a page


● Changing the style and position of displayed elements
Performed by dynamically
Client side ● Modifying a page in response to events

Scripts ● Getting browser information


● Making the Web page different depending on the
browser and browser features
● Generating HTML code for parts of the page
Pros:
●Allow for more interactivity by immediately responding to
users’ actions.
●Execute quickly because they do not require a trip to the
server.
Pros & Cons ●The web browser uses its own resources, and eases the
of Client side burden on the server.
Scripts ●It saves network bandwidth.
Cons:
●Code is loaded in the browser so it will be visible to the client.
●Code is modifiable.
●Local files and databases cannot be accessed.
●User is able to disable client side scripting
Server side scripting Client side scripting
Server side scripting is used to create Client side scripting is used when the
dynamic pages based on a number of users
conditions when the users browser makes browser already has all the code and the
a page is altered on the basis of the users
request to the server. Input.
The Web Server executes the server side The Web Browser executes the client side
Client V/S scripting that produces the page to be sent
to the browser.
scripting that resides at the user’s
computer.

Server Side Server side scripting is used to connect to


the databases and files that reside on the
Client side scripting cannot be used to
connect to the databases and files on the
Scripting web server.
Server resources can be accessed by the
web server.
Browser resources can be accessed by
server side scripting. the
client side scripting.
Server side scripting can’t be blocked by Client side scripting is possible to be
the blocked
user. by the user.
Examples of Server side scripting Examples of Client side scripting
languages : languages :
PHP, JSP, ASP, ASP.Net, Ruby, Perl and Javascript, VB script, etc.
many
more.
● The <script> tag is used to define a client-side script
(JavaScript).
● The <script> element either contains scripting
statements, or it points to an external script file
through the src attribute.
● Example : Internal JS External JS
<html>
<html>

<script> tag <head>


<head>
<title>HTML script Tag</title>
<title>HTML script Tag</title>
</head>
</head>
<body>
<body>
<script type="text/javascript">
<script src=“PathToJS”>
// Java Script Code Here
</script>
</script>
</body>
</body>
</html>
</html>
● A variable can contain several types of value:
● Number : a numeric value e.g. 156, 100, 1.2
● String : character wrapped in quotes e.g. “rajkot”
● Boolean : a value of true or false
● Null : an empty variable
● Function : a function name
Variable ● Object : an object
● Attributes of Javascript variables :
● It is a case sensitive. (mynum and MyNum are
different variables)
● It cannot contain punctuation, space or start with a
digit
● It cannot be a JavaScript reserved word
● If condition: If ..else , if….elseif….if
if(a>10)
{
alert(“A is > that 10”);
}
● Ternary operator:
max = a>b ? a : b ;
● Switch:
Conditional switch(expression)

Statements {
case lbl1:
// code to execute
break;
case lbl2:
// code to execute
break;
}
for loop

Use when you know how


many repetitions you
want
do while loop
to do while loop
Execute block at least once
syntax Loops through block of code then repeat while condition
while condition is true is true
for(initialize ; condition ;
increment) { … } syntax syntax

Loops example while(condition) { … } do{ … } while (condition);


for(x=0;x<10;x++) { example example
// Code Here
} while (x<10) { do{
var person= { fname:”A”, //Code Here // Code Here
lname:”b” age:25};
for( x in person) } } while (x<10)
{
t= t+person[x];
}
● A string can be defined as a sequence of letters,
digits, punctuation and so on.
● A string in a JavaScript is wrapped with single or
double quotes
● Strings can be joined together with the + operator,
which is called concatenation.

String ● For Example,


mystring = “my college name is ” + “SVNIT”;
● As string is an object type it also has some useful
features.
● For Example,
lenStr = mystring.length;
● Which returns the length of the string in integer
Method Description

charAt Returns the character at a specific index

indexOf Find the first index of a character

lastIndexOf Find the last index of a character


String substring / Return a section of a string.
substr
replace Replaces a specified value with another value in a
string
toLowerCase Convert a string to lower case.

toUpperCase Convert a string to upper case.


● An escape sequence is a sequence of characters that
does not represent itself when used inside a character
or string, but is translated into another character or a
sequence of characters that may be difficult or
impossible to represent directly.
● Some Useful Escape sequences :

Character Description

String \t Tab

\n Newline

\r Carriage return

\” Double Quote

\’ Single Quote

\\ Backslash
● An array is a collection of data, each item in array has
an index to access it.
● Ways to use array in JavaScript
Array ● var myArray = new Array();
● myArray[0] = “darshan”;
● myArray[1] = 222;
● myArray[2] = false;
● var myArray = new Array(“darshan” , 123 , true);
● A JavaScript function is a block of code designed to
perform a particular task.
● A JavaScript function is executed when "something"
invokes it.
● A JavaScript function is defined with the function
keyword, followed by a name, followed by parentheses
().
● The parentheses may include parameter names
Function separated by commas: (parameter1, parameter2, ...)
● The code to be executed, by the function, is placed
inside curly brackets.
● Example :
function myFunction(p1, p2)
{
return p1 * p2;
}
● 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
Function invoking statement.
● 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)
● Popup boxes can be used to raise an alert, or to get
confirmation on any input or to have a kind of input
from the users.
Popup Boxes ● JavaScript supports three types of popup boxes.
● Alert box
● Confirm box
● Prompt box
● An alert box is used if you want to make sure
information comes through to the user.
● When an alert box pops up, the user will have to click
"OK" to proceed.
● It can be used to display the result of validation.
● Example:
Alert Box
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<script>
alert("Hello World");
</script>
</body>
</html>
● A confirm box is used if you want the user to accept
something.
● When a confirm box pops up, the user will have to
click either"OK" or "Cancel" to proceed, If the user
clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
● Example :

Confirm Box
<script>
var a = confirm(“Are you sure??");
if(a==true) {
alert(“User Accepted”);
}
else {
alert(“User Cancled”);
}
</script>
● A prompt box is used if you want the user to input a
value.
● When a prompt box pops up, user have to click either
"OK" or"Cancel" to proceed, If the user clicks "OK" the
box returns the input value, If the user clicks "Cancel"
the box returns null.

Prompt Box
<script>

var a = prompt(“Enter Name");

alert(“User Entered ” + a);

</script>
● We can create external JavaScript file and embed it in
many html pages.
● It provides code reusability because single JavaScript
file can be used in several html pages.
● An external JavaScript file must be saved by .js
External extension.
Javascript ● To embed the External JavaScript File to HTML we can
use script tag with src attribute in the head section to
specify the path of JavaScript file.
● For Example :
● <script type="text/javascript"
src="message.js"></script>
message.js
function myAlert(msg) {

if(confirm("Are you sure you want to display the message????")) {


alert(msg);
}
else {
alert("Message not Displayed as User Cancled Operation");
}

External
Javascript
Myhtml.html
<html>
<head>
<script src=“message.js”></script>
</head>
<body>
<script> myAlert(“Hello World”); </script>
</body>
</html>
● An object is just a special kind of data, with properties
and methods.
Accessing Object Properties
● Properties are the values associated with an object.
● The syntax for accessing the property of an object is
Javascript below
Objects objectName.propertyName
● This example uses the length property of the
Javascript’s inbuilt
object(String) to find the length of a string:
var message="Hello World!";
var x=message.length;
● The Math object allows you to perform mathematical
tasks.
● The Math object includes several mathematical
Javascript constants and methods.

inbuilt ● Example for using properties/methods of Math:

Objects: <script>

Math var x=Math.PI;


var y=Math.sqrt(16);

</script>
● Math object has some properties which are,

Properties Description

LN10 Returns the natural logarithm of 10 (approx.2.302)

Javascript LOG2E Returns the base‐2 logarithm of E (approx.1.442)

LOG10E Returns the base‐10 logarithm of E (approx.0.434)


inbuilt PI Returns PI(approx.3.14)

Objects: SQRT1_2 Returns square root of ½

Math SQRT2 Returns square root of 2

LN2 Returns the natural logarithm of 2 (approx.0.693)

E Returns Euler's number(approx.2.718)


Method Description
● Math
abs(x) object has some
Returns properties
the absolute value of x which are,

random(x) Returns random floating number between 0 to 1

sin(x) Returns the sine of x (x is in radians)

cos(x) Returns the cosine of x (x is in radians)

Javascript tan(x) Returns the tan of x (x is in Radians)

inbuilt acos(x)

asin(x)
Returns the arccosine of x, in radians

Returns the arcsine of x, in radians


Objects: atan(x) Returns the arctangent of x as a numeric value

Math exp(x) Returns the value of Ex

methods sqrt(x)

max(x,y, z,...,n)
Returns the square root of x

Returns the number with the highest value

pow(x,y) Returns the value of x to the power of y

round(x) Rounds x to the nearest integer

log(x) Returns the natural logarithm(base E) of x

floor(x) Returns x, rounded downwards to the nearest integer

ceil(x) Returns x, rounded upwards to the nearest integer


● JavaScript allows you to create your own objects.
● The first step is to use the new operator.
var myObj= new Object();
● This creates an empty object.
User defined ● This can then be used to start a new object that you
Objects can then give new properties and methods.
● In object- oriented programming such a new object is
usually given a constructor to initialize values when it
is first created.
● However, it is also possible to assign values when it is
made with literal values.
<script>

person={

firstname: “A",

User defined lastname: “B",

Objects age: 50,

eyecolor: "blue"

alert(person.firstname + " is " + person.age + " years old.");

</script>
● A constructor is pre defined method that will initialize
your object.
● To do this in JavaScript a function is used that is
invoked through the new operator.
● Any properties inside the newly created object are
assigned using this keyword, referring to the current
object being created.
User defined <script>
Objects function person(firstname, lastname, age){
this.firstname = firstname;
this.lastname = lastname;
this. changeFirstName = function (name){ this.firstname = name };
}
var person1=new person("Narendra","Modi",50);
person1.changeFirstName(“NAMO”);
alert(person1.firstname + “ ”+ person1.lastname);
</script>
● The Document Object Model is a platform and
language neutral interface that will allow programs
and scripts to dynamically access and update the
content, structure and style of documents.
● The window object is the primary point from which
most other objects come.
Document ● From the current window object access and control
Object Model can be given to most aspects of the browser features
and the HTML document.
(DOM) ● When we write :
document.write(“Hello World”);
● We are actually writing :
window.document.write(“Hello World”);
● The window is just there by default
● This window object represents the window or frame
that displays the document and is the global object in
client side programming for JavaScript.
Document ● All the client side objects are connected to the window
object.
Object Model
(DOM)
Property Description

forms Returns a collection of all the forms in the


document
images Returns a collection of all the images in the
document
links Returns a collection of all the links in the
document (CSSs)
Document referrer Returns the URL of the document that loaded the
current document
Object title Sets or returns the title of the document
Properties URL Returns the full URL of the document
Domain Returns the domain name of the server that
loaded the document
Cookie Returns all name/value pairs of cookies in the
document
body Returns the body element of the document
applets Returns a collection of all the applets in the
document
anchors Returns a collection of all the anchors in the
Method Description

write() Writes HTML expressions or JavaScript code


to a
document
writeln() Same as write(), but adds a newline
character
after each statement
Document open() Opens an output stream to collect the output
from document.write() or document.writeln()
Object close() Closes the output stream previously opened
Properties with
document.open()
getElementById() Accesses element with a specified id
getElementsByName() Accesses all elements with a specified name
getElementsByTagNa Accesses all elements with a specified tag
me() name
setTimeout() Set a time period for calling a function once;
or
cancel it.
● When we suppose to get the reference of the element
from HTML in JavaScript using id specified in the HTML
we can use this method.
● Example :

getElementBy
<script>
Id() <html> function myFunction()
<body> {
<input type=“text” id=“myText”> var txt =
<input type=“button” document.getElementById(“my
onClick=“myFunction()”> Text”);
</body> alert(txt.value);
</html> }
</script>
● When we suppose to get the reference of the
elements from HTML in JavaScript using name
specified in the HTML we can use this method.
● It will return the array of elements with the provided
name.
● Example :

getElementsB <html>
<script>
yName() <body>
function myFunction()
{
<input type=“text”
a=document.getElementsByNa
name=“myText”>
me(“myText”)[0];
<input type=“button”
alert(a.value);
onClick=“myFunction()”>
}
</body>
</script>
</html>
● When we suppose to get the reference of the
elements from HTML in JavaScript using name of the
tag specified in the HTML we can use this method.
● It will return the array of elements with the provided
tag name
● Example :
getElementsB
yTagName() <html> <script>
<body> function myFunction() {
<input type=“text” a=document.getElementsByTag
name=“uname”> Name(“input”);
<input type=“text” alert(a[0].value);
name=“pword”> alert(a[1].value);
</body> }
</html> </script>
● We can access the elements of form in DOM quite
easily using the name/id of the form.
● Example :

function f()
{
<html>
var a =
<body>
document.forms[“myForm”];
Forms using <form name=“myForm”>
<input type=“text”
var u = a.uname.value;
var p = a.pword.value;
DOM name=“uname”>
<input type=“text”
if(u==“admin” && p==“123”)
{
name=“pword”>
alert(“valid”);
<input type=“button”
}
onClick=“f()”>
else
</form>
{
</body>
alert(“Invalid”);
</html>
}
}
● Validation is the process of checking data against a
standard or requirement.
● Form validation normally used to occur at the server,
after client entered necessary data and then pressed
the Submit button.
● If the data entered by a client was incorrect or was
Validation simply missing, the server would have to send all the
data back to the client and request that the form be
resubmitted with correct information.
● This was really a lengthy process which used to put a
lot of burden on the server.
● JavaScript provides a way to validate form's data on
the client's computer before sending it to the web
server.
● Form validation generally performs two functions.
● Basic Validation
● Emptiness
● Confirm Password
● Length Validation etc……
Validation ● Data Format Validation
● Secondly, the data that is entered must be checked for
correct form and value.
● Email Validation
● Mobile Number Validation
● Enrollment Number Validation etc….
● A regular expression is an object that describes a
pattern of characters.
● Regular expressions are used to perform pattern-
matching and "search-and-replace" functions on text.
● Example:
var pattern = "^ [\\w]$"; // will allow only words in the
Validation string
using RegExp var regex = new RegExp(pattern);
If(regex.test(testString)){
//Valid
} else {
//Invalid
}
● To find word characters in the string we can use \w
● We can also use [a-z], [A-Z] or [a-zA-Z] for the same
● To find non-word characters in the string we can use \
Validation W

using RegExp ● to find digit characters in the string we can use \d


● We can also use [0-9] for the same
● To find non-digit characters in the string we can use \D
● We can use \n for new line and \t for tab
Quantifier Description

n$ Matches any string with n at the end of it


^n Matches any string with n at the beginning of it
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y
Validation n's
n{X,} Matches any string that contains a sequence of at
using RegExp least X n's
n? Matches any string that contains zero or one
occurrences of n
n* Matches any string that contains zero or more
occurrences of n

n+ Matches any string that contains at least one n


<script>

function checkMail()

Email var a = document.getElementById("myText").value;

var pattern ="^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$”;


Validation var regex = new RegExp(pattern);
Using RegExp if(regex.test(a))
{
alert("Valid");
}
else
{
alert("Invalid");
}
}
</script>
<html>

<body>

<div id=“myDiv”>

Red Alert !!!!!!

</div>

<script>
DHTML var objDiv = document.getElementById(“myDiv”);

var colors = [‘white’,’yellow’,’orange’,’red’];

var nextColor = 0;

setInterval(“objDiv.style.backgroundColor =
colors[nextColor++%colors.length];”,500);

</script>

</body>

</html>
DHTML – ● DHTML, or Dynamic HTML, is really just a combination
of HTML, JavaScript and CSS.
Combining ● The main problem with DHTML, which was introduced
HTML,CSS & in the 4.0 series of browsers, is compatibility.

JS ● The main focus generally when speaking of DHTML is


animation and other such dynamic effects.
● We can obtain reference of any HTML or CSS element
in
● JavaSCript using below 3 methods.
document.getElementById(“IdOfElement”)
document.getElementsByName(“NameOfElement”)
document.getElementsByTagName(“TagName”)
DHTML – ● After obtaining the reference of the element you can
Combining change the attributes of the same using
reference.attribute syntax
HTML,CSS & ● For Example :
JS <img src=“abc.jpg” id=“myImg”>

<script>
var a = document.getElementById(‘myImg’);
a.src = “xyz.jpg”;
</script>
Event Description

id Sets or returns the id of an element


HTML innerHTML Sets or returns the HTML contents (+text) of an
Element Style
element
Sets or returns the style attribute of an element
Properties tabIndex Sets or returns the tab order of an element
title Sets or returns the title attribute of an element
Value Sets or returns the value attribute of an element
className Sets or returns the class attribute of an element
Event Attribute Description

click onclick The event occurs when the user clicks


on an element
dblclick ondblclick The event occurs when the user
double-clicks on an element
mousedown onmousedown The event occurs when a user
presses a mouse button over an
Mouse Events element
mousemove onmousemove The event occurs when a user moves
the mouse pointer over an element
mouseover onmouseover The event occurs when a user mouse
over an Element
mouseout onmouseout The event occurs when a user moves
the mouse pointer out of an element
mouseup onmouseup The event occurs when a user
releases a mouse button over an
element
Event Attribute Description

Keyboard keydown onkeydown The event occurs when the user is


pressing a key or holding down a key
Events keypress onkeypress The event occurs when the user is
pressing a key or holding down a key
keyup onkeyup The event occurs when a keyboard
key is
Event Attribute Description

abort onabort The event occurs when an image is


stopped from loading before
completely loaded (for <object>)
error onerror The event occurs when an image
does not load properly (for <object>,
<body> and <frameset>)
Frame/Object load onload The event occurs when a document,
Events frameset, or <object> has been loaded
resize onresize The event occurs when a document
view is resized
scroll onscroll The event occurs when a document
view is scrolled
unload onunload The event occurs when a document is
removed from a window or frame (for
<body> and
Event Attribute Description

blur onblur The event occurs when a form


element loses focus
change onchange The event occurs when the content of
a form element, the selection, or the
checked state have changed (for
<input>, <select>, and <textarea>)
Form Events focus onfocus The event occurs when an element
gets focus (for <label>, <input>,
<select>, textarea>, and <button>)
reset onreset The event occurs when a form is reset
select onselect The event occurs when a user selects
some text (for <input> and <textarea>)
submit onsubmit The event occurs when a form is
submitted
#Thank You
From @:Darsha
☺☺☺

You might also like