What is JavaScript?
 JavaScript is a client-side object-oriented scripting

language that is used to add interactivity to...
How to embed JavaScript in HTML?
 Scripts are embedded inside the HTML file using the

script tag <script>.

Scripts
Inte...
Where to embed JavaScript in HTML?
 Script tag can be added either inside <head> section or the

<body> section of the HT...
JavaScript Syntax
 JavaScript statements ends with ;
 JavaScript is case sensitive
 JavaScript comments are like C++ an...
JavaScript Output
 Writing to The HTML Document Output:
 To write HTML element using JavaScript we user
document.write("...
JavaScript Output (Cont.)
 NOTE:

If you execute document.write after the document has
finished loading, the entire HTML ...
JavaScript Output (Cont.)
JavaScript Variables
 Variable names must begin with a letter or $ or _.
 JavaScript is a weakly-typed language, meaning...
JavaScript Objects
 To Create Object and add properties to it:
1.
var person = {
firstname : "John",
lastname : “Adam",
a...
JavaScript Functions
 Syntax:

function functionname(argument1, argument2, …)
{
// some code to be executed
return value;...
JavaScript Operators
 JavaScript arithmetic operators (like C++ and Java):





+
/
*
++
-%
JavaScript assignment ope...
JavaScript Conditions
 If...else if...else Statement:
 Syntax:
if (condition1)
{
// code to be executed if condition1 is...
JavaScript Conditions (Cont.)
 Switch Statement:
 Syntax:
switch(n)
{
case 1:
// execute code block 1
break;
case 2:
// ...
JavaScript Loops
 For Loop:
 Syntax:
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
 For ...
JavaScript Loops (cont.)
 While Loop:
 Syntax:
while (condition)
{
// code block to be executed
}
 Do .. While Loop:
 ...
JavaScript Break and Continue
 Break Statement:
 It breaks the loop and continues executing the code after
the loop (if ...
JavaScript Strings
 String Length:
 You can get the length of a string using length property.
 Example:
var txt="Hello ...
JavaScript Strings (Cont.)
 Matching Content:
 You can search for a matching content in a string using match()
method.
...
JavaScript Strings (Cont.)
 Upper Case and Lower Case:
 You can convert a string to upper/lower case with the
methods to...
JavaScript Strings (Cont.)
 Take part from a String:
 You can take part from a string using substring() method.
 Exampl...
JavaScript Strings (Cont.)
 Concatenate two Strings:
 You can concatenate two strings using concat()
method.
 Example:
...
JavaScript Date
 Initiating a date:
1.
new Date(); // current date and time
2.
new Date(dateString);
3.
new, Date(year mo...
JavaScript Date (Cont.)
 Set Date:
1. setFullYear(year, month, day):
Example:
var myDate=new Date();
myDate.setFullYear(2...
JavaScript Date (Cont.)
 getDate() Method:
 Used to get the day from a date.
 getMonth() Method :
 Used to get the mon...
JavaScript Math
 The Math object includes several mathematical constants

and methods.
 Math.PI:
 Constant 3.14




...
JavaScript HTML DOM
 The HTML DOM (Document Object Model) is a standard

for how to interact with (get, change, add, or d...
JavaScript HTML DOM (Cont.)
 Example - Return the value of each element in

the form :
JavaScript HTML DOM (Cont.)
<html>
<body>
<form id="frm">
First name: <input type="text" name="fname" value="Donald"><br>
...
JavaScript HTML DOM (Cont.)
 To access the value of the first name in the previous

example:
 var firstName = document.f...
JavaScript HTML DOM (Cont.)
 Changing HTML:
 Changing the HTML Output Stream:


document.write()

 Changing HTML Conte...
JavaScript HTML DOM (Cont.)
 Events:
 Examples of HTML events:







When a user clicks the mouse
When a web page...
JavaScript HTML DOM (Cont.)
 Mostly used Events:








Onclick
Onload
Onchange
Onmouseover
Onmouseout
Onmousedow...
JavaScript BOM
 BOM stands for Browser Object Model.
 Window:
 Window Size:




For Chrome, Firefox, Opera, and Safar...
JavaScript Browser BOM (Cont.)
 Some Window Methods:
 window.open()
 window.close()
 window.resizeTo()
 Window Frames...
JavaScript Browser BOM (Cont.)
 Popup Alert:
 Alert Box:



Syntax: window.alert(“Message");
A popup with ok button.

...
JavaScript Browser BOM (Cont.)
 Location:
 Syntax: window.location or location
 location.href: returns the URL of the c...
JavaScript Browser BOM (Cont.)
 History:
 history.back(): same as clicking back in the browser.
 history.forward(): sam...
TASK
 Create a page like the following, and
then validate for empty fields.
 On Submit:
1.
If Username is empty: Alert
“...
TASK (Cont.)
<html>
<head>
<script type="text/javascript">
function validateForm(){
var username = document.forms["myForm"...
TASK (Cont.)
<body>
<form name="myForm" onsubmit="return
validateForm()">
Username: <input type="text" name="username"><br...
 Java script
Upcoming SlideShare
Loading in...5
×

Java script

679

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
679
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
25
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Java script

  1. 1. What is JavaScript?  JavaScript is a client-side object-oriented scripting language that is used to add interactivity to static HTML pages.  JavaScript is mainly used for validating user input in web forms, reacting to user events, detecting browsers, etc…
  2. 2. How to embed JavaScript in HTML?  Scripts are embedded inside the HTML file using the script tag <script>. Scripts Internal The JavaScript code is embedded inside the HTML file as follows: <script type=”text/javascript”> // JavaScript code goes here </script> External The JavaScript code is written in an external file with extension “.js” and referenced in the HTML file as follows: <script type=”text/javascript” src=”scriptFile.js”/>
  3. 3. Where to embed JavaScript in HTML?  Script tag can be added either inside <head> section or the <body> section of the HTML page. Scripts In Body In Head Scripts added to the <head> section are to be executed when called. Scripts added to the <body> section are to be executed when the page loads.  Scripts are better to be included at the end of the HTML page in order to prevent slow loading of pages.
  4. 4. JavaScript Syntax  JavaScript statements ends with ;  JavaScript is case sensitive  JavaScript comments are like C++ and Java comments // for single line comments and /* */ for multi-line comments
  5. 5. JavaScript Output  Writing to The HTML Document Output:  To write HTML element using JavaScript we user document.write("HTML Element");  Example – To write a paragraph using JavaScript: <script type=”text/javascript”> document.write("<p>JavaScript Paragraph</p>"); </script>
  6. 6. JavaScript Output (Cont.)  NOTE: If you execute document.write after the document has finished loading, the entire HTML page will be overwritten.  Example: <p>My Paragraph.</p> <button onclick="myFunction()">Try it</button> <script type=”text/javascript”> function myFunction() { document.write("<p>Oops! The document disappeared!</p>"); } </script>
  7. 7. JavaScript Output (Cont.)
  8. 8. JavaScript Variables  Variable names must begin with a letter or $ or _.  JavaScript is a weakly-typed language, meaning that variables are declared without specifying data-types.  You can declare variables with the var keyword.  Examples: var x = 1; var y = 1.2; var str = "Hello World"; var check = "true"; var cars=new Array("Saab", "Volvo", "BMW");  Note: If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBALvariable.
  9. 9. JavaScript Objects  To Create Object and add properties to it: 1. var person = { firstname : "John", lastname : “Adam", age : 50 }; 2. Var person = new Object(); person.firstname="John"; person.lastname=“Adam"; person.age=50;  To Access Object properties: 1. 2. name=person.lastname; name=person["lastname"];
  10. 10. JavaScript Functions  Syntax: function functionname(argument1, argument2, …) { // some code to be executed return value; }  To call: var returnVar = functionname(argument1, argument2, …);
  11. 11. JavaScript Operators  JavaScript arithmetic operators (like C++ and Java):     + / * ++ -% JavaScript assignment operators (like C++ and Java): = += -= /= JavaScript logical operators (like C++ and Java): && || ! JavaScript string concatenation operator: + JavaScript comparison operators : != == > < <= >= === !==
  12. 12. JavaScript Conditions  If...else if...else Statement:  Syntax: if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if neither condition1 nor condition2 is true }
  13. 13. JavaScript Conditions (Cont.)  Switch Statement:  Syntax: switch(n) { case 1: // execute code block 1 break; case 2: // execute code block 2 break; default: // code to be executed if n is different from case 1 and 2 }
  14. 14. JavaScript Loops  For Loop:  Syntax: for (statement 1; statement 2; statement 3) { // code block to be executed }  For .. In Loop:  Syntax: for (variable in object) { // code to be executed }  Example: var person={fname:"John", lname:“Adam", age:25}; for (x in person) { var personElement = person[x]; }
  15. 15. JavaScript Loops (cont.)  While Loop:  Syntax: while (condition) { // code block to be executed }  Do .. While Loop:  Syntax: do { // code block to be executed } while (condition);
  16. 16. JavaScript Break and Continue  Break Statement:  It breaks the loop and continues executing the code after the loop (if any).  Syntax: break;  Continue Statement:  It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.  Syntax: continue;
  17. 17. JavaScript Strings  String Length:  You can get the length of a string using length property.  Example: var txt="Hello World"; document.write(txt.length);  11  Finding a String in a String:  You can find a string in another string using either indexOf() or lastIndexOf() method.  The method returns -1 if the specified text is not found.  Example: var str="Hello world"; var n = str.indexOf("l");  2 var m = str.lastIndexOf("l");  9
  18. 18. JavaScript Strings (Cont.)  Matching Content:  You can search for a matching content in a string using match() method.  This method returns the matching content if present, else it returns null.  Example: var str="Hello World"; document.write(str.match("world"));  null document.write(str.match("World"));  World  Replacing Content:  You can replace a specified value with another value in a string using replace() method.  Example: var str=“Hello World" var n=str.replace(“World",“FCI");  Hello FCI
  19. 19. JavaScript Strings (Cont.)  Upper Case and Lower Case:  You can convert a string to upper/lower case with the methods toUpperCase() / toLowerCase().  Example: var txt="Hello World"; var txt1=txt.toUpperCase();  HELLO WORLD var txt2=txt.toLowerCase();  hello world  Convert a String to an Array:  You can convert a string to an array with split() method.  Example: var str="a,b,c,d,e,f“; var arr=str.split(",");  array {“a”, “b”, “c”, “d”, “e”, “f”}
  20. 20. JavaScript Strings (Cont.)  Take part from a String:  You can take part from a string using substring() method.  Example: var str="Hello World"; var substr=str.substring(2, 5);  llo  Get Character from a String:  You can get a char from a string using charAt() method.  Example: var str="Hello World"; var c=str.charAt(1);  e
  21. 21. JavaScript Strings (Cont.)  Concatenate two Strings:  You can concatenate two strings using concat() method.  Example: var txt1="Hello"; var txt2="World"; var txt = txt1.concat(txt2);  HelloWorld
  22. 22. JavaScript Date  Initiating a date: 1. new Date(); // current date and time 2. new Date(dateString); 3. new, Date(year month, day, hours, minutes, seconds);  Example: var n = new Date(79,5,24,11,33,o); document.write(n); Result: Sun Jun 24 1979 11:33:00 GMT+0200 (Egypt Standard Time)  Example: var n = new Date("June 24, 1979 11:33:00"); document.write(n); Result: Sun Jun 24 1979 11:33:00 GMT+0200 (Egypt Standard Time)
  23. 23. JavaScript Date (Cont.)  Set Date: 1. setFullYear(year, month, day): Example: var myDate=new Date(); myDate.setFullYear(2010,0,14); 1. setDate(dateobject): Example: var myDate=new Date(); myDate.setDate(myDate.getDate()+5);  Compare Two Dates:  To compare dates use >, <, ==, <=, >=
  24. 24. JavaScript Date (Cont.)  getDate() Method:  Used to get the day from a date.  getMonth() Method :  Used to get the month from a date.  Note: Month starts from zero so add 1 to the retrun result.  getFullYear() Method :  Used to get the year from a date.
  25. 25. JavaScript Math  The Math object includes several mathematical constants and methods.  Math.PI:  Constant 3.14       Math.round(number). Math.floor(number). Math.ceil(number). Math.max(number1, number2). Math.min(number1, number2). Math.random():  Return a random number between 0 and 1.
  26. 26. JavaScript HTML DOM  The HTML DOM (Document Object Model) is a standard for how to interact with (get, change, add, or delete) HTML elements.  Finding HTML Elements: 1. 2. 3. By Id:  document.getElementById(“id"); By Tag Name:  document.getElementsByTagName(“tag"); By HTML Object Collections:  The following HTML object collections are accessible: • • • • document.anchors document.forms document.images document.links
  27. 27. JavaScript HTML DOM (Cont.)  Example - Return the value of each element in the form :
  28. 28. JavaScript HTML DOM (Cont.) <html> <body> <form id="frm"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br> <input type="submit" value="Submit" onClick="printValues()"> </form> <script type="text/javascript"> function printValues() { var form = document.forms["frm"]; for (var i=0 ; i < form.length ; i++) { document.write(form.elements[i].value); document.write("<br>"); } } </script> </body> </html>
  29. 29. JavaScript HTML DOM (Cont.)  To access the value of the first name in the previous example:  var firstName = document.forms[“frm"]["fname"].value;
  30. 30. JavaScript HTML DOM (Cont.)  Changing HTML:  Changing the HTML Output Stream:  document.write()  Changing HTML Content:  document.getElementById(id).innerHTML=new HTML  Changing the Value of an Attribute:  document.getElementById(id).attribute=new value
  31. 31. JavaScript HTML DOM (Cont.)  Events:  Examples of HTML events:       When a user clicks the mouse When a web page has loaded When an image has been loaded When the mouse moves over an element When an input field is changed When an HTML form is submitted  Assign Events:  Using Attributes:   Example: <button id= "myBtn" onclick="displayDate()">Try it</button> Using HTML DOM:  Example: document.getElementById("myBtn").onclick=function(){displayDate() };
  32. 32. JavaScript HTML DOM (Cont.)  Mostly used Events:        Onclick Onload Onchange Onmouseover Onmouseout Onmousedown Onmouseup
  33. 33. JavaScript BOM  BOM stands for Browser Object Model.  Window:  Window Size:   For Chrome, Firefox, Opera, and Safari:  window.innerHeight - the inner height of the browser window  window.innerWidth - the inner width of the browser window For Internet Explorer 8, 7, 6, 5:  document.documentElement.clientHeight  document.documentElement.clientWidth or  document.body.clientHeight  document.body.clientWidth
  34. 34. JavaScript Browser BOM (Cont.)  Some Window Methods:  window.open()  window.close()  window.resizeTo()  Window Frames:  window.frames  Screen:  Syntax: window.screen or screen  To get the available screen width and height (Without taskbars or scrolling bars):   screen.availWidth screen.availHeight
  35. 35. JavaScript Browser BOM (Cont.)  Popup Alert:  Alert Box:   Syntax: window.alert(“Message"); A popup with ok button.  Confirm Box:   Syntax: window.confirm(“Message"); A popup with ok and cancel buttons, returns true if the user clicked on ok and false if the user clicked on cancel.  Prompt Box:   Syntax: window.prompt(“Message","Default value for input"); A popup with a text box for user input, ok and cancel buttons, returns the user input if he user clicked ok and null if the user clicked on cancel.  NOTE: To display line breaks inside a popup box, use n.
  36. 36. JavaScript Browser BOM (Cont.)  Location:  Syntax: window.location or location  location.href: returns the URL of the current page.  location.pathname: returns the path and filename of the current page.  location.hostname: returns the domain name of the web host.  location.port: returns the port of the web host (80 or 443).  location.protocol: returns the web protocol used (http:// or https://).  location.assign(URL): loads a new page.
  37. 37. JavaScript Browser BOM (Cont.)  History:  history.back(): same as clicking back in the browser.  history.forward(): same as clicking forward in the browser.
  38. 38. TASK  Create a page like the following, and then validate for empty fields.  On Submit: 1. If Username is empty: Alert “Username must be filled out.”. 2. If Password is empty: Alert “Password must be filled out.”. 3. Else: Alert “Done.”. What needed to be known? •To define a variable: var variable_name = variable_value; •To define a function: function function_name(parameters…) { // Code goes here return value; } •To get form: document.forms[“form id“]; •To get value of element in form: document.forms[“form id“][“name attribute of the element”].value; •To Alert a message: Alert(“Message”);
  39. 39. TASK (Cont.) <html> <head> <script type="text/javascript"> function validateForm(){ var username = document.forms["myForm"]["username"].value; var password = document.forms["myForm"]["password"].value if (username == null || username == "") { alert("Username must be filled out."); return false; } else if (password == null || password == "") { alert("Password must be filled out."); return false; } else { alert("Done."); return true; } } </script> </head>
  40. 40. TASK (Cont.) <body> <form name="myForm" onsubmit="return validateForm()"> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="Submit"> </form> </body> </html>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×