introduction to javascript
DESCRIPTION
INTRODUCTION TO JAVASCRIPT. JAVASCRIPT. JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more. - PowerPoint PPT PresentationTRANSCRIPT
INTRODUCTION INTRODUCTION TO JAVASCRIPTTO JAVASCRIPT
JAVASCRIPTJAVASCRIPT
►JavaScript is used in millions of JavaScript is used in millions of Web pages to improve the design, Web pages to improve the design, validate forms, detect browsers, validate forms, detect browsers, create cookies, and much more.create cookies, and much more.
►JavaScript is the most popular JavaScript is the most popular scripting language on the scripting language on the internet, and works in all major internet, and works in all major browsers, such as Internet browsers, such as Internet Explorer, Mozilla, Firefox, Explorer, Mozilla, Firefox, Netscape, Opera.Netscape, Opera.
WHAT IS JAVASCRIPT?WHAT IS JAVASCRIPT?
► JavaScript was designed to add interactivity to JavaScript was designed to add interactivity to HTML pages HTML pages
► JavaScript is a scripting language (a scripting JavaScript is a scripting language (a scripting language is a lightweight programming language) language is a lightweight programming language)
► A JavaScript consists of lines of executable A JavaScript consists of lines of executable computer code computer code
► A JavaScript is usually embedded directly into A JavaScript is usually embedded directly into HTML pages HTML pages
► JavaScript is an interpreted language (means that JavaScript is an interpreted language (means that scripts execute without preliminary compilation) scripts execute without preliminary compilation)
► Everyone can use JavaScript without purchasing a Everyone can use JavaScript without purchasing a license license
What is JavaScript? (cont)What is JavaScript? (cont)
►Object based (not object oriented) Object based (not object oriented) programming languageprogramming language very limited object creationvery limited object creation a set of pre-defined objects associated a set of pre-defined objects associated
withwith►HTML document structureHTML document structure
many HTML tags constitute JS Objects many HTML tags constitute JS Objects
►Browser functionalityBrowser functionality provides a limited API to Browser functionalityprovides a limited API to Browser functionality
Where did it come fromWhere did it come from
► Originally called LiveScript at NetscapeOriginally called LiveScript at Netscape started out to be a server side scripting language started out to be a server side scripting language
for providing database connectivity and dynamic for providing database connectivity and dynamic HTML generation on Netscape Web ServersHTML generation on Netscape Web Servers
Netscape decided it would be a good thing for their Netscape decided it would be a good thing for their browsers and servers to speak the same language browsers and servers to speak the same language so it got included in Navigatorso it got included in Navigator
Netscape in alliance w/Sun jointly announced the Netscape in alliance w/Sun jointly announced the language and its new name Java Scriptlanguage and its new name Java Script
Because of rapid acceptance by the web Because of rapid acceptance by the web community Microsoft forced to include in IE community Microsoft forced to include in IE BrowserBrowser
Browser compatibilityBrowser compatibility
►For the most part Java Script runs the For the most part Java Script runs the same way in all popular browserssame way in all popular browsers
►There are many areas where there are There are many areas where there are slight differences in how Java Script slight differences in how Java Script will runwill run
►there will be a separate set of slides there will be a separate set of slides addressing these differences.addressing these differences.
JavaScript…Java ?JavaScript…Java ?
►There is no relationship other than the There is no relationship other than the fact that Java and JavaScript resemble fact that Java and JavaScript resemble each other (and C++) syntacticallyeach other (and C++) syntactically
► JavaScript is pretty much the de-facto JavaScript is pretty much the de-facto standard for client-side scripting (Internet standard for client-side scripting (Internet Explorer also provides VBScript & JScript)Explorer also provides VBScript & JScript)
► In Netscape browsers there is an API that In Netscape browsers there is an API that allows JavaScript and Java applets allows JavaScript and Java applets embedded in the same page to converse embedded in the same page to converse
What can it be used forWhat can it be used for
►Some pretty amazing things….Some pretty amazing things…. Text animationText animation graphic animationgraphic animation simple browser based applicationsimple browser based application HTML forms submission HTML forms submission client-side forms data validation (relieving client-side forms data validation (relieving
the server of this task)the server of this task) web site navigationweb site navigation
What do I need to get startedWhat do I need to get started
►A web browserA web browser Netscape Navigator 4.x or laterNetscape Navigator 4.x or later MS Internet Explorer 3.x or laterMS Internet Explorer 3.x or later
►A text EditorA text Editor Wordpad/NotepadWordpad/Notepad Vi, EmacsVi, Emacs
Putting JavaScript into your Putting JavaScript into your HTMLHTML
► in an external filein an external file collect commonly used functions together collect commonly used functions together
into external function libraries on the serverinto external function libraries on the server►added benefit of privacy from curious usersadded benefit of privacy from curious users
► in-line with your HTMLin-line with your HTML►as an expression for an HTML tag as an expression for an HTML tag
attributeattribute►within some HTML tags as Event Handlerswithin some HTML tags as Event Handlers
ProcessProcess
►Open your text editorOpen your text editor►create a file containing html and create a file containing html and
JavascriptJavascript►save as text file with file type .htm save as text file with file type .htm
or .htmlor .html►open your browseropen your browser►click on file, open fileclick on file, open file
locate the file you just createdlocate the file you just created
►open file in browseropen file in browser
<SCRIPT>…</SCRIPT><SCRIPT>…</SCRIPT>
►<SCRIPT language=…. src=……></SCRIPT><SCRIPT language=…. src=……></SCRIPT>► The <SCRIPT> tag indicates to the browser The <SCRIPT> tag indicates to the browser
the beginning of an embedded script; the beginning of an embedded script; </SCRIPT> indicates the end of an </SCRIPT> indicates the end of an embedded script.embedded script.
► the “language” attribute indicates the script the “language” attribute indicates the script processor to be usedprocessor to be used
► the “src” attribute indicates the URL of a file the “src” attribute indicates the URL of a file on the server containing the script to be on the server containing the script to be embedded embedded
ScriptsScripts
►Since scripts are placed in line with Since scripts are placed in line with with HTML older browsers will attempt with HTML older browsers will attempt to submit them as text.to submit them as text.
►To prevent this hide them in side of To prevent this hide them in side of an HTML comment . <!-- -->an HTML comment . <!-- -->
►for JavaScript comments use // or /* */for JavaScript comments use // or /* */
<SCRIPT><SCRIPT>
►<SCRIPT LANGUAGE=“JavaScript”><SCRIPT LANGUAGE=“JavaScript”>►<!-- start hiding code from old browsers><!-- start hiding code from old browsers>► ScriptScript► CodeCode►GoesGoes►HereHere► // Stop Hiding code -->// Stop Hiding code -->►</SCRIPT></SCRIPT>
Document Object model Document Object model (DOM)(DOM)► Java Script enabled browsers are capable of Java Script enabled browsers are capable of
recognizing individual objects in HTML page, recognizing individual objects in HTML page, after the page has been submitted in the after the page has been submitted in the browsers, because the java script enabled browsers, because the java script enabled browsers recognizes and uses DOM.browsers recognizes and uses DOM.
► Using the DOM , java script enabled browsers Using the DOM , java script enabled browsers identify the collection of web page objects.identify the collection of web page objects.
► Java script objects hierarchy is mapped to the Java script objects hierarchy is mapped to the Dom, which in turns mapped to web page Dom, which in turns mapped to web page elements in the browsers window.elements in the browsers window.
Object HierarchyObject Hierarchy
window
link anchor layer form applet image area
history document location link
text radio button fileUpload select
textarea
password
checkbox reset
submit
option
The Object ModelThe Object Model
► It is very important to understand the It is very important to understand the object modelobject model
►each object has its own properties, each object has its own properties, some of which are read only some of some of which are read only some of which you can set directly by which you can set directly by assignment (as location) assignment (as location)
►each object also has a set of behaviors each object also has a set of behaviors called methods called methods
Are Java and JavaScript the Are Java and JavaScript the Same? Same?
►NO!NO!► Java and JavaScript are two completely Java and JavaScript are two completely
different languages in both concept different languages in both concept and design!and design!
► Java (developed by Sun Microsystems) Java (developed by Sun Microsystems) is a powerful and much more complex is a powerful and much more complex programming language - in the same programming language - in the same category as C and C++.category as C and C++.
How to Put a JavaScript Into an How to Put a JavaScript Into an HTML Page?HTML Page?
<html><html>
<body><body>
<script type="text/javascript"><script type="text/javascript">
document.write("Hello World!")document.write("Hello World!")
</script></script>
</body></body>
</html> </html>
OUTPUTOUTPUT
Ending Statements With a Ending Statements With a Semicolon? Semicolon?
►With traditional programming languages, With traditional programming languages, like C++ and Java, each code statement like C++ and Java, each code statement has to end with a semicolon (;).has to end with a semicolon (;).
►Many programmers continue this habit Many programmers continue this habit when writing JavaScript, but in general, when writing JavaScript, but in general, semicolons are semicolons are optionaloptional! However, ! However, semicolons are required if you want to semicolons are required if you want to put more than one statement on a single put more than one statement on a single line.line.
JavaScript Variables JavaScript Variables
► Variables are used to store data. Variables are used to store data. ► A variable is a "container" for information you A variable is a "container" for information you
want to store. A variable's value can change want to store. A variable's value can change during the script. You can refer to a variable during the script. You can refer to a variable by name to see its value or to change its by name to see its value or to change its value.value.
► Rules for variable names:Rules for variable names: Variable names are case sensitive Variable names are case sensitive They must begin with a letter or the underscore They must begin with a letter or the underscore
character character ► strname – STRNAME (not same)strname – STRNAME (not same)
JavaScript OperatorsJavaScript Operators
Arithmetic OperatorsArithmetic Operators Operator Description Example Result
+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division remainder)
5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
JavaScript Operators – 2JavaScript Operators – 2
Assignment OperatorsAssignment OperatorsOperator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
JavaScript Operators - 3JavaScript Operators - 3
Comparison Comparison OperatorsOperators
Operator Description Example
== is equal to 5==8 returns false
=== is equal to (checks for both value and type)
x=5
y="5"
x==y returns true
x===y returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to
5>=8 returns false
<= is less than or equal to 5<=8 returns true
JavaScript Operators - 4JavaScript Operators - 4
Logical OperatorsLogical Operators Operator Description Example
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
JavaScript Basic ExamplesJavaScript Basic Examples
<script><script>
document.write("Hello World!")document.write("Hello World!")</script> </script> format text with HTML code - headingformat text with HTML code - heading
<script><script>
alert("Hello World!")alert("Hello World!")
</script></script>
ExampleExample<html><html><body><body><script><script>x="Hello World!"x="Hello World!"document.write(x)document.write(x)document.write("<br>")document.write("<br>")</script></script>
<script><script>x="GOOD BYE"x="GOOD BYE"document.write("CLASS" +x)document.write("CLASS" +x)</script> </script>
</body></body></html> </html>
OUTPUTOUTPUT
JavaScript Popup Boxes JavaScript Popup Boxes
►Alert BoxAlert Box An alert box is often used if you want to An alert box is often used if you want to
make sure information comes through to make sure information comes through to the user.the user.
When an alert box pops up, the user will When an alert box pops up, the user will have to click "OK" to proceed. have to click "OK" to proceed.
<script><script>
alert("Hello World!")alert("Hello World!")
</script></script>
JavaScript Popup Boxes - 2JavaScript Popup Boxes - 2
►Confirm Box Confirm Box A confirm box is often used if you want A confirm box is often used if you want
the user to verify or accept something.the user to verify or accept something. When a confirm box pops up, the user will When a confirm box pops up, the user will
have to click either "OK" or "Cancel" to have to click either "OK" or "Cancel" to proceed. proceed.
If the user clicks "OK", the box returns If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box true. If the user clicks "Cancel", the box returns false.returns false.
JavaScript Popup Boxes - 3JavaScript Popup Boxes - 3
►Prompt BoxPrompt Box A prompt box is often used if you want the A prompt box is often used if you want the
user to input a value before entering a user to input a value before entering a page.page.
When a prompt box pops up, the user will When a prompt box pops up, the user will have to click either "OK" or "Cancel" to have to click either "OK" or "Cancel" to proceed after entering an input value. proceed after entering an input value.
If the user clicks "OK“, the box returns the If the user clicks "OK“, the box returns the input value. If the user clicks "Cancel“, the input value. If the user clicks "Cancel“, the box returns null.box returns null.
Prompt Box ExamplePrompt Box Example
<script><script>
x=prompt (“x=prompt (“WELCOMEWELCOME”, “ ”)”, “ ”)
document.write(“document.write(“CLASSCLASS <br>”,+x) <br>”,+x)
</script></script>
OUTPUTOUTPUT
OUTPUTOUTPUT
OUTPUTOUTPUT
JS Examples -1JS Examples -1
Y=20x+12Y=20x+12 ;where ;where x=3 x=3
<script><script>
x=3x=3
y=20*x+12y=20*x+12
alert(y)alert(y)
</script></script>
OUTPUTOUTPUT
Examples -2Examples -2
<script><script>
s1=12s1=12
s2=28s2=28
toplam=s1+s2toplam=s1+s2
document.write("Sayıların toplamı: document.write("Sayıların toplamı: "+toplam)"+toplam)
</script></script>
Examples -3Examples -3
<script><script>s1=12s1=12s2=6s2=6add=s1+s2add=s1+s2sub=s1-s2sub=s1-s2mul=s1*s2mul=s1*s2divl=s1/s2divl=s1/s2document.write(add+"<br>")document.write(add+"<br>")document.write(sub+"<br>")document.write(sub+"<br>")document.write(mul+"<br>")document.write(mul+"<br>")document.write(divl+"<br>")document.write(divl+"<br>")alert("CACULATION COMPLETED")alert("CACULATION COMPLETED")</script ></script ></script ></script >
s1=12, s2=28s1=12, s2=28
OUTPUTOUTPUT
Conditional StatementsConditional Statements► Very often when you write code, you want to perform different Very often when you write code, you want to perform different
actions for different decisions. You can use conditional actions for different decisions. You can use conditional statements in your code to do this.statements in your code to do this.
In JavaScript we have the following conditional statements:In JavaScript we have the following conditional statements:► if statementif statement - use this statement if you want to execute - use this statement if you want to execute
some code only if a specified condition is true some code only if a specified condition is true ► if...else statementif...else statement - use this statement if you want to - use this statement if you want to
execute some code if the condition is true and another code if execute some code if the condition is true and another code if the condition is false the condition is false
► if...else if....else statementif...else if....else statement - use this statement if you - use this statement if you want to select one of many blocks of code to be executed want to select one of many blocks of code to be executed
► switch statementswitch statement - use this statement if you want to select - use this statement if you want to select one of many blocks of code to be executed one of many blocks of code to be executed
Conditional Statements - 2Conditional Statements - 2if (if (conditioncondition)){{code to be executed if condition is truecode to be executed if condition is true
}}
if (if (conditioncondition)){{code to be executed if condition is truecode to be executed if condition is true}}elseelse{{code to be executed if condition is not truecode to be executed if condition is not true} }
Conditional Statements Conditional Statements ExamplesExamples
<script><script>x=3x=3if(x<0)if(x<0){{alert ("negative")alert ("negative")}}elseelse{{alert ("pozitive")alert ("pozitive")}}</script></script>
OUTPUTOUTPUT
Conditional Statements Conditional Statements Examples - 2Examples - 2
<script><script>c=confirm(“c=confirm(“IS 25 divisible by 5 IS 25 divisible by 5 ?”)?”)if(c)if(c){{alert (“alert (“Correct answerCorrect answer”)”)}}elseelse{{alert (“alert (“wrong answerwrong answer”)”)}}</script></script>
OUTPUTOUTPUT
OUTPUTOUTPUT
Conditional Statements Conditional Statements Examples - 3Examples - 3
<script><script>p=prompt(“p=prompt(“ENTER THE MARKSENTER THE MARKS?", " ")?", " ")if(pif(p>=>=““5050")"){{alert(“alert(“PASSPASS")")}}elseelse{{alert(“alert(“FAILFAIL")")}}</script></script>
OUTPUTOUTPUT
OUTPUTOUTPUT