Java Script Class 1
Java Script Class 1
JavaScript is THE scripting language of the Web. JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.
What is JavaScript?
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license
Java
Java Script
The code is compiled andClient interprets it but does not downloaded from the server,compile. but executed at the client. Java is a Object OrientedIt is Object based language. language. Objects are dividedInheritance is through the into classes and instances withprototype mechanism and all inheritance through the classproperties and methods can be hierarchy. Properties andadded to any object methods cannot be added todynamically. classes and instances dynamically. Java applets are distinct fromThe Java Script code is HTML, but are accessed fromintegrated with and embedded HTML. in HTML. Variable data types must declared beVariable data types need not to be declared.
It is Early binding. ObjectIt is Late binding. Object reference must exist at compilereferences checked at run time. time.
ECMAScript language standard. ECMA-262 is the official JavaScript standard. JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all browsers since 1996. The official standardization was adopted by the ECMA organization (an industry standardization association) in 1997. The ECMA standard (called ECMAScript-262) was approved as an international ISO (ISO/IEC 16262) standard in 1998. The development is still in progress.
JavaScript How To
The HTML <script> tag is used to insert a JavaScript into an HTML document. The HTML "id" attribute is used to identify HTML elements.
Example : Access the HTML element with the specified id, and change its content
<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p id="demo">My First Paragraph</p> <script type="text/javascript"> document.getElementById("demo").innerHTML=" My First JavaScript"; </script> </body> </html>
JavaScript Where To
JavaScripts can be put in the <body> and in the <head> sections of an HTML page.
JavaScript in <body>
The example below manipulate the content of an existing <p> element when the page loads: <!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <script type="text/javascript"> document.getElementById("demo").innerHTML=" My First JavaScript"; </script> </body> </html> Note: The JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created.
Example
<!DOCTYPE html> <html> <body> <script type="text/javascript" src="myScript.js"></script> </body> </html>
Note: You can place the script in the head or body as you like. Note: The script will behave as it was located in the document, exactly where you put it.
JavaScript Statements
JavaScript is a sequence of statements to be executed by the browser. JavaScript is Case Sensitive. A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do. This JavaScript statement tells the browser to write "Hello Dolly" to an HTML element: document.getElementById("demo").in nerHTML="Hello Dolly";
It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web. The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Note: Using semicolons makes it possible to write multiple statements on one line.
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is executed by the browser in the sequence they are written. This example will manipulate two HTML elements: document.getElementById("demo").inne rHTML="Hello Dolly"; document.getElementById("myDIV").inn erHTML="How are you?;
JavaScript Blocks
JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket {, and end with a right curly bracket }. The purpose of a block is to make the sequence of statements execute together. An example of statements grouped together in blocks, are JavaScript functions. This example will run a function that
JavaScript Comments
JavaScript comments can be used to make the code more readable. Single line comments start with //. Multi line comments start with /* and end with */.
JavaScript Variables
Variables are "containers" for storing information. A variable can have a short name, like x, or a more descriptive name, like carname. Rules for JavaScript variable names:
Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter, the $ character, or the underscore character
<!DOCTYPE html> <html> <body> <p>Click the button to create a variable, and display the result.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var carname="Volvo"; document.getElementById("demo").innerHTML=carname; } </script> </body> </html>
Note: When you assign a text value to a variable, put quotes around the value. Note: When you assign a numeric value to a variable, do not put quotes around the value, if you put quotes around a numeric value, it will be treated as text. Note: If you redeclare a JavaScript variable, it will not lose its value.
JavaScript Arithmetic
you can do arithmetic operations with JavaScript variables:
<!DOCTYPE html> <html> <body> <p>Given that y=5, calculate x=y+2, and display the result.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var y=5; var x=y+2;
JavaScript Operators
= is used to assign values. +, -, *, / (gives float values), %, ++, --, +=, -=,*=, /+,%=. + operator can also be used on strings to concatenation. txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; (or) txt3=txt1+" "+txt2;
Adding two numbers, will return the sum, but adding a number and a string will return a string: x=5+5; y="5"+5; z="Hello"+5; Resulted as 10 55 Hello5
Comparison and Logical operators are used to test for true or false. if (age<18) x="Too young";
Conditional Operator:
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax: variablename=(condition)?value1:value2 Ex: voteable=(age<18)?"Too young":"Old
If Statement
if (condition) { code to be executed if condition is true } if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }
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 }
<!DOCTYPE html> <html> <body> <p>Click the button to get a time-based greeting.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x=""; var time=new Date().getHours(); if (time<10) { x="Good morning"; }
else if (time<20) { x="Good day"; } else { x="Good evening"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script type="text/javascript"> var r=Math.random(); var x=document.getElementById("demo") if (r>0.5) { x.innerHTML="<a href='http://w3schools.com'>Visit W3Schools</a>"; } else { x.innerHTML="<a href='http://wwf.org'>Visit WWF</a>"; } </script> </body> </html>
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 }
how it works:
First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. Use the default keyword to specify what to do if there is no match
{ case 0: x="Today it's Sunday"; break; case 1: x="Today it's Monday"; break; case 2: x="Today it's Tuesday"; break; case 3: x="Today it's Wednesday"; break; case 4: x="Today it's Thursday"; break;
case 5: x="Today it's Friday"; break; case 6: x="Today it's Saturday"; break; default: x="Looking forward to the Weekend"; } document.getElementById ("demo").innerHTML=x; } </script> </body> </html>
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function myFunction() { alert("I am an alert box!"); } </script> </head> <body> <input type="button" onclick="myFunction()" value="Show alert box" /> </body> </html>
Confirm Box
A confirm box is often used if you want the user to verify or 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. Syntax: confirm("sometext");
var r=confirm("Press a button"); if (r==true) { x="You pressed OK!"; } else { x="You pressed Cancel!"; }
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax:
var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") { x="Hello " + name + "! How are you today?"; } Line Breaks : To display line breaks inside a popup box, use a back-slash followed by the character n. Syntax: alert("Hello\nHow are you?");
JavaScript Functions
A function can be executed by an event, like clicking a button. A function is a block of code that executes only when you tell it to execute. It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function. Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made.
Syntax: function functionname() { some code } Calling a Function with Arguments : When you call a function, you can pass along some values to it, these values are called arguments or parameters. These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,). Ex: myFunction(argument1,argument2) Declare the argument, as variables, when you declare the function: function myFunction(var1,var2) { some code }
Ex: <button onclick="myFunction('Harry Potter','Wizard')">Try it</button> <script type="text/javascript"> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script>
The function-call will be replaced with the return value: var myVar=myFunction(); The variable myVar holds the value 5, which is what the function "myFunction()" returns. You can also use the returnvalue without storing it as a variable: document.getElementById("demo").i nnerHTML=myFunction();
function myFunction(a,b) { return a*b; } document.getElementById("demo").i nnerHTML=myFunction(4,3); The innerHTML of the "demo" element will be: 12
The return statement is also used when you simply want to exit a function. The return value is optional: function myFunction(a,b) { if (a>b) { return; } x=a+b } The function above will exit the function if a>b, and will not calculate the sum of a and b.
Example: <!DOCTYPE html> <html> <body> <p>Click the button to loop through a block of code five times.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x="",i; for (i=0;i<5;i++) { x=x + "The number is " + i + "<br />"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>
do { x=x + "The number is " + i + "<br />"; i++; } while (i<5); The break Statement : The break statement will break the loop and continue executing the code that follows after the loop (if any).
for (i=0;i<10;i++) { if (i==3) { break; } x=x + "The number is " + i + "<br />"; } The continue Statement: The continue statement will break the current loop and continue with the next value. for (i=0;i<=10;i++) { if (i==3) { continue; } x=x + "The number is " + i + "<br />"; }
JavaScript Events
Events are actions that can be detected by JavaScript. <!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayDate() { document.getElementById("demo").innerHTML=D ate(); } </script> </head> <body> <h1>My First Web Page</h1> <p id="demo"></p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html>
Events
By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Examples of events:
A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input field in an HTML form Submitting an HTML form A keystroke
Events are normally used in combination with functions, and the function will not be executed before the event occurs! onLoad and onUnload:
The onLoad and onUnload events are triggered when the user enters or leaves the page. The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".
onSubmit:
The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.htm" onsubmit="return checkForm()">
onMouseOver:
The onmouseover event can be used to trigger a function when the user mouses over an HTML element.
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function writeText(txt) { document.getElementById("desc").innerHTML=txt; } </script> </head> <body> <img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" /> <map name="planetmap"> <area shape ="rect" coords ="0,0,82,126" onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by far the largest objects in our Solar System.')" href ="sun.htm" target ="_blank" alt="Sun" />
<area shape ="circle" coords ="90,58,3" onmouseover="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')" href ="mercur.htm" target ="_blank" alt="Mercury" /> <area shape ="circle" coords ="124,58,8" onmouseover="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')" href ="venus.htm" target ="_blank" alt="Venus" /> </map> <p id="desc">Mouse over the sun and the
The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. try { //Run some code here } catch(err) { //Handle errors here }
<!DOCTYPE html> <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); //Here we written alert function spelled wrongly. } catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.message + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>
The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:
<!DOCTYPE html> <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n";
txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www.w 3schools.com/"; } } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>
<!DOCTYPE html> <html> <body> <script type="text/javascript"> var x=prompt("Enter a number between 5 and 10:",""); try { if(x>10) { throw "Err1"; } else if(x<5) { throw "Err2"; } else if(isNaN(x)) { throw "Err3"; } }
catch(err) { if(err=="Err1") { document.write("Error! The value is too high."); } if(err=="Err2") { document.write("Error! The value is too low."); } if(err=="Err3") { document.write("Error! The value is not a number."); } } </script> </body> </html>
Outputs single quote double quote backslash new line carriage return tab backspace form feed