Javascript PPT - I am Programmer

advertisement
WTP
Unit 4
JavaScript and DHTML
• Javascript:
–
–
–
–
–
–
–
–
–
–
–
–
Client side scripting,
What is Javascript,
How to develop Javascript,
Simple Javascript,
Variables,
Functions,
Conditions,
Loops and repetition,
Javascript: Advance script, Javascript and objects,
Javascript own objects,
The DOM and web browser environments,
Forms and validations
• DHTML :
– Combining HTML, CSS and Javascript,
– Events and buttons,
– Controlling your browser
Client-side Scripting
• Client-side scripts, which run on the user’s
workstation can be used to:
– Validate user inputs entered on HTML forms
– Create advanced Web page features, including:
• Handling manipulation of the browser (opening new ones,
redirection …)
• Creating “cookies” that store data on user’s computer about his or
her actions while browsing a Web page
• Create animations and graphical effects
JavaScript
• Can be Server-side scripting language too
• Can be added to standard HTML Web pages
using special HTML tags
• Used in Web pages for data validation
• Used to create pop-up browser windows
• Animations, games, dynamic graphics
JavaScript has three parts
1) Core: Includes operators, expressions,
statements and subprograms
2) Client-side: Collection of objects which can
control over browser and user-browser
interaction is possible
3) Server-side: Collection of objects using to
access the database on the server
Java vs. JavaScript
Java
JavaScript
Programming language
Scripting language ,Interpreted (not
compiled)
Object oriented language
NO
Strongly typed, type checking is done
at compile time
Weakly typed, checking the
compatibility of type can be done
dynamically
Where to put your script?
– JavaScript programs can be used in two
ways:
• Incorporated directly into an HTML file
– Using <script type=“text/javascript”> tag
– Using <script language=“javascript”> tag
• Placed in an external (source) file
– Has file extension .js
– Contains only JavaScript statements
– Using <script src=“example.js”></script>
Advantages of a JS Source File
• Makes HTML document neater (less
confusing)
• JS can be shared among multiple HTML files
• Can use a combination of embedded and
non–embedded code
How to write?
• Placing JavaScript in <head> or <body>
sections
– Script statements interpreted in order of
document rendering
– <head> section rendered before <body> section
• Good practice to place as much code as possible in
<head> section
A JavaScript Program in Head Tag
<HTML>
<HEAD>
<TITLE>A First Program in JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT TYPE="text/javascript">
document.write(“Hello world ! – From body Tag.” );
</SCRIPT>
</BODY>
</HTML>
A JavaScript Program in Body tag
<HTML>
<HEAD>
<TITLE>A First Program in JavaScript</TITLE>
<SCRIPT TYPE="text/javascript">
document.write( “Hello world ! – From Head Tag.” );
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Reserved Words
• Special words associated with special meaning
1.
2.
3.
4.
5.
6.
break
case
catch
do
default
for
7.
8.
9.
10.
11.
12.
function
new
return
throw
var
void
Variables
• Names given to variables, holds data value
1. Variables begins with either letter,
underscore or dollar sign
2. No limit on the length
3. Case-sensitive
– VVP x VvP x vVP
Variable Declaration
• No data type is required.
• Example, declaring variables within a Script:
var variable1;
var variable1,variable2;
• Example, initialising variables within a Script:
variable1 = 0;
variable2 = “Hello”;
Primitives types (Variables)
Functions
JavaScript, like a lot of programming languages,
uses functions.
The basic format is :
function function-name ( parameters ) {
lines of code
}
Function Example
<head>
<p>The function returns a text.</p>
<script type="text/javascript">
<script type="text/javascript">
function myFunction()
{
document.write(myFunction())
</script>
return ("Hello, have a nice day!")
}
</script>
</head>
<body>
<p>The script in the body section calls a
function.</p>
</body>
</html>
CONVERTING AND EVALUATING
VARIABLES AND EXPRESSIONS
• parseInt – convert string to int
• parseFloat – convert string to float
• eval – convert string to numbers
Dialog Boxes
• alert() used to display message.
• prompt() allows user enter something.
• confirm() used to get user confirmation.
1 ALERT DIALOG BOX
– The Alert dialog box is used to display some
textual information on the web browser.
– The dialog box will have only one button ‘OK’.
– Example
<script language="javascript">
alert(“Hi, How are You");
</script>
2 CONFIRM DIALOG BOX
• A confirm box is often used if you want the user
to verify or accept something. A confirm box
display the predefine message and ‘OK’ and
‘CANCEL’ button.
• Example
<script language="javascript">
if(confirm(“Do you want to accept it?"))
document.write(“You pressed ok")
• </script>
3 PROMPT DIALOG BOX
• A prompt box is often used if you want the user to
input a value before entering a page. A prompt box
display a predefine message, a textbox for user input
and display ok and cancel button.
• Example
name = prompt("Enter your name", "First name")
document.write("Welcome " + name)
IF statements
if (condition) {
//statements1
}
else {
//statements2
}
SWITCH statement
switch (expression){
case label : statement;
break;
case label : statement;
break;
default : statement;
}
Loops & Repetition
DO WHILE statement
Do {
} while(condition)
WHILE statement
while (condition) {
statements
}
FOR statement
for ([initial-expression]; [condition]; [increment-expression]) {
//statements
}
User-Defined Objects
• JavaScript is an Object Based Scripting
language.
• JavaScript allows you to define your own
objects and make your own variable types.
• Note that an object is just a special kind of
data. An object has properties and methods.
Object: Properties
• Properties are the values associated with an
object.
• In the following example we are using the
length property of the String object to return
the number of characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
Object: Methods
• Methods are the actions that can be
performed on objects.
• In the following example we are using the
toUpperCase() method of the String object to
display a text in uppercase letters:
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
JavaScript Objects
• A person is an object. Properties are the values
associated with the object.
• The persons' properties include name, height,
weight, age, skin tone, eye color, etc. All persons
have these properties, but the values of those
properties will differ from person to person.
• Objects also have methods. Methods are the
actions that can be performed on objects. The
persons' methods could be eat(), sleep(), work(),
play(), etc.
DOM and Web Browser Environments
• What is the DOM?
The
Document
Object
Model
is
an
API
for HTML and XML documents. It provides a structural
representation of the document, enabling you to modify its
content and visual presentation. Essentially, it connects web
pages to scripts or programming languages.
• It defines the logical structure of documents and the way a
document is accessed and manipulated.
• With the Document Object Model, programmers can build
documents, navigate their structure, and add, modify, or
delete elements and content.
A graphical representation of the DOM of the example table is:
The Document Object Model
• Root level of the JavaScript DOM is the window
object
• Window objects have properties such as status
line
• The next level up is the document object…which
is the loaded HTML page
• Document objects have properties such as
background colour
• Each HTML element (e.g. links or forms) is a
property of the document object.
Javascript Document Object Model
Document properties
• The first image on a web page can be
represented as the property
document.images[0]
• A web form also has its properties accessible
in the object tree
• You can find any property by tracing it
through the tree:
document.forms[0].elements[0]
Events
• It describes actions that occur as a result of user
interaction with the web page or other browser related
activities. Example : When a button is clicked or a
mouse has been moved or even when a key has been
pressed an event is said to be occurred.
• Events are built into the HTML code, not within script
tags.
• Multiple events can be active
<INPUT TYPE="text" size="30" onClick="alert('You are
about to enter Name')" onChange="alert('Name has
been changed.')">
<html>
Events & Functions
<head>
<script type="text/javascript">
function myfunction()
{
alert("HELLO");
}
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction()" value="Call function">
</form>
<p>By pressing the button, a function will be called. The function will alert a message.</p>
</body>
</html>
Controlling your browser
How to Scroll a Page With JavaScript
• This example demonstrates how to use the
JavaScript scrollBy and setTimeout methods
to make a web page scroll down
automatically.
function pageScroll() {
window.scrollBy(0,50); // horizontal and vertical scroll
increments scrolldelay = setTimeout('pageScroll()',100); //
scrolls every 100 milliseconds
}
Controlling your browser
• To being scrolling automatically when the page loads, add the
following code to the body tag:
<body onLoad="pageScroll()">
• To begin scrolling when prompted by the user, call the
function from a link or button:
Text Link
<a href="javascript:pageScroll()">Scroll Page</a>
• Scroll Page (Note: If you click this link, you'll need to click the
link at the bottom of the page to cancel the scrolling)
Controlling your browser
Button
<input type="button" onClick="pageScroll()" value="Scroll
Page">
Stop Scrolling
• The pageScroll() function causes the page to keep scrolling
forever. The following function will stop the scrolling, and can
be called in the same way:
function stopScroll() {
clearTimeout(scrolldelay); }
<a href="javascript:stopScroll()">Stop Scrolling</a>
Controlling your browser
Scroll Directly to a Particular Point
• Use the scroll() method to jump to a particular point on the
page. The target position is specified in pixels from the top left
corner of the page, horizontally and vertically.
function jumpScroll() {
window.scroll(0,150); // horizontal and vertical scroll targets }
<a href="javascript:jumpScroll()">Jump to another place on
the page</a>
GTU Questions
• What do you mean by event in JavaScript? Give at least two examples of
events with their handling. (GTU-2011 May)
07
• Write a JavaScript program to print first N odd numbers divisible by 07
(GTU-2011 May)
• Answer the following questions with respect to JavaScript. 07
1. Give the different purpose for which Javascripts are used.
2. Writing user defined objects in JavaScript. (GTU-2011 May)
• Write an HTML form accepting an integer having 4-digits. Provide 07
necessary validations using JavaScript. Input should not accept characters.
(GTU-2011 May)
• Write a program using Java Script, which sorts elements of an array in
descending order using bubble sort. (GTU-2011 Nov)
07
• What are objects in Java Script? Explain properties,
methods and 07
event of window object of Java Script. (GTU-2011 Nov)
• Create a HTML page with Java Script, which takes one
integer
number as input and tells whether the number
is even or odd. 07 (GTU-2011 Nov)
• What is JavaScript ? Explain Variable Scope and assignment
with Example. (GTU-2013) 07
• Create HTML Page with JavaScript which takes Integer
number as input and tells whether the number is Prime or
Not. (GTU-2013) 07
• Create HTML Page with JavaScript which takes Integer
number as input and tells whether the number is ODD or
EVEN. (GTU-2013) 07
• Explain Array, Function with Example (with reference to
JavaScript). (GTU-2013) 07
Thank You
Download