2.94k likes | 3.09k Views
Java Script Tutorial. by Mohammad Abdollahi http://www.abdollahi.us. Subjects. JS Basic JS Objects JS Advanced. JS Basic. JS Introduction JS How To JS Where To JS Statements JS Comments JS Variables
E N D
Java Script Tutorial by Mohammad Abdollahi http://www.abdollahi.us
Subjects JS Basic JS Objects JS Advanced
JS Basic JS IntroductionJS How ToJS Where ToJS StatementsJS CommentsJS Variables JS Data TypesJS OperatorsJS ComparisonsJS If...ElseJS SwitchJS Popup BoxesJS Functions JS For LoopJS While LoopJS Break LoopsJS For...InJS EventsJS Try...CatchJS ThrowJS Special TextJS Guidelines
JS Introduction • 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 You Should Already Know • Before you continue you should have a basic understanding of the following: • HTML and CSS
JS IntroductionWhat 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
JS IntroductionAre Java and JavaScript the same? • NO! • Java and JavaScript are two completely different languages in both concept and design! • Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
JS IntroductionWhat Can JavaScript do? • JavaScript gives HTML designers a programming tool • HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages.
JS IntroductionWhat Can JavaScript do? • JavaScript can react to events • A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element. • JavaScript can manipulate HTML elements • A JavaScript can read and change the content of an HTML element.
JS IntroductionWhat Can JavaScript do? • JavaScript can be used to validate data • A JavaScript can be used to validate form input. • JavaScript can be used to detect the visitor's browser • A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser • JavaScript can be used to create cookies • A JavaScript can be used to store and retrieve information on the visitor's computer
JS IntroductionJavaScript = ECMAScript • JavaScript is an implementation of the 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 ToManipulating HTML Elements • The HTML <script> tag is used to insert a JavaScript into an HTML document. • The HTML "id" attribute is used to identify HTML elements. • JavaScript is typically used to manipulate existing HTML elements.
JavaScript How ToManipulating HTML Elements • The HTML "id" attribute is used to identify HTML elements. • To access an HTML element from a JavaScript, use the document.getElementById() method. • The document.getElementById() method will access the HTML element with the specified id.
JavaScript How ToManipulating 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 How ToManipulating HTML Elements • Example Explained • To insert a JavaScript into an HTML page, use the <script> tag. • Inside the <script> tag use the type attribute to define the scripting language. • The <script> and </script> tells where the JavaScript starts and ends. • The lines between the <script> and </script> contain the JavaScript and are executed by the browser:
JavaScript How ToManipulating HTML Elements • Example Explained • To insert a JavaScript into an HTML page, use the <script> tag. • Inside the <script> tag use the type attribute to define the scripting language. • The <script> and </script> tells where the JavaScript starts and ends. • The lines between the <script> and </script> contain the JavaScript and are executed by the browser • In this case, the browser will access the HTML element with id="demo", and replace the content with "My First JavaScript".
JavaScript How ToSome Browsers do Not Support JavaScript • Browsers that do not support JavaScript, will display JavaScript as page content. • To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript. • Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, like this:
JavaScript How ToSome Browsers do Not Support JavaScript <!DOCTYPE html><html> <body> <script type="text/javascript"> <!--document.getElementById("demo").innerHTML="My First JavaScript"; //--> </script> </body></html> The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.
JavaScript How ToWrite Directly into The HTML Document • The example below writes a <p> element into the HTML document: • Example <!DOCTYPE html><html> <body> <h1>My First Web Page</h1> <script type="text/javascript">document.write("<p>My First JavaScript</p>"); </script> </body></html> The entire HTML page will be overwritten if document.write() is used inside a function
JavaScript Where ToJavaScript in <body> • The example below manipulate the content of an existing <p> element when the page loads: • Example <!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> The JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created.
JavaScript Where ToJavaScript Functions and Events • The JavaScript statement in the example above, is executed when the page loads, but that is not always what we want. • Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. • Then we put the script inside a function. • Functions are normally used in combination with events. • You will learn more about JavaScript functions and events in later chapters.
JavaScript Where ToJavaScript Functions in <body> • This example also calls a function when a button is clicked, but the script is placed at the bottom of the page: • Example <!DOCTYPE html><html><body> <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <button type="button" onclick="myFunction()">Try it</button> <script type="text/javascript">function myFunction(){document.getElementById("demo").innerHTML="My First JavaScript Function";}</script> </body></html>
JavaScript Where ToScripts in <head> and <body> • You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time. • It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
JavaScript Where ToUsing an External JavaScript • JavaScript can also be placed in external files. • External JavaScript files often contain code to be used on several different web pages. • External JavaScript files have the file extension .js. • Note: External script cannot contain the <script></script> tags! • To use an external script, point to the .js file in the "src" attribute of the <script> tag:
JavaScript Where ToUsing an External JavaScript • 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 Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions.
JavaScript Statements • 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").innerHTML="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. Because of this you will often see examples without the semicolon at the end. • Note: Using semicolons makes it possible to write multiple statements on one line.
JavaScript StatementsJavaScript 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: • Example document.getElementById("demo").innerHTML="Hello Dolly";document.getElementById("myDIV").innerHTML="How are you?";
JavaScript StatementsJavaScript 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 will manipulate two HTML elements:
JavaScript StatementsJavaScript Blocks • Example function myFunction(){document.getElementById("demo").innerHTML="Hello Dolly";document.getElementById("myDIV").innerHTML="How are you?";}
JavaScript Comments • JavaScript comments can be used to make the code more readable. • Comments will not be executed by JavaScript. • Comments can be added to explain the JavaScript, or to make the code more readable. • Single line comments start with //. • The following example uses single line comments to explain the code:
JavaScript Comments • Example // Write to a heading:document.getElementById("myH1").innerHTML="Welcome to my Homepage";// Write to a paragraph:document.getElementById("myP").innerHTML="This is my first paragraph.";
JavaScript CommentsJavaScript Multi-Line Comments • Multi line comments start with /* and end with */. • The following example uses a multi line comment to explain the code: • Example /*The code below will writeto a heading and to a paragraph,and will represent the start ofmy homepage:*/document.getElementById("myH1").innerHTML="Welcome to my Homepage";document.getElementById("myP").innerHTML="This is my first paragraph.";
JavaScript CommentsUsing Comments to Prevent Execution • In the following example the comment is used to prevent the execution of one of the codelines (can be suitable for debugging): • Example //document.getElementById("myH1").innerHTML="Welcome to my Homepage";document.getElementById("myP").innerHTML="This is my first paragraph."; • In the following example the comment is used to prevent the execution of a code block (can be suitable for debugging): • Example /*document.getElementById("myH1").innerHTML="Welcome to my Homepage";document.getElementById("myP").innerHTML="This is my first paragraph.";*/
JavaScript CommentsUsing Comments at the End of a Line • In the following example the comment is placed at the end of a code line: • Example var x=5; // declare a variable and assign a value to itx=x+2; // Add 2 to the variable x
JavaScript Variables Do You Remember Algebra From School? • Do you remember algebra from school? x=5, y=6, z=x+y • Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could use the information above to calculate the value of z to be 11? • These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y). • Variables are "containers" for storing information.
JavaScript Variables • As with algebra, JavaScript variables are used to hold values or expressions. • 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 • Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
JavaScript Variables Declaring (Creating) JavaScript Variables • Creating a variable in JavaScript is most often referred to as "declaring" a variable. • You declare JavaScript variables with the var keyword: varcarname; • After the declaration shown above, the variable is empty (it has no value yet). • To assign a value to the variable, use the equal (=) sign: carname="Volvo";
JavaScript Variables Declaring (Creating) JavaScript Variables • However, you can also assign a value to the variable when you declare it: varcarname="Volvo"; • After the execution of the statement above, the carname will hold the value Volvo. • To write the value inside an HTML element, simply refer to it by using it's variable name: • Example varcarname="Volvo";document.getElementById("myP").innerHTML=carname;
JavaScript Variables Declaring (Creating) JavaScript Variables • 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 Variables Local JavaScript Variables • A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. (the variable has local scope). • You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. • Local variables are deleted as soon as the function is completed. • You will learn more about functions in a later chapter of this tutorial.
JavaScript Variables Global JavaScript Variables • Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it. • Global variables are deleted when you close the page.
JavaScript VariablesAssigning Values to Undeclared JavaScript Variables • If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables. • This statement: carname="Volvo"; • will declare the variable carname as a global variable (if it does not already exist).
JavaScript Data TypesJavaScript is Weakly Typed • String, Number, Boolean, Array, Object, Null, Undefined. • JavaScript is weakly typed. This means that the same variable can be used as different types: • Example var x// Now x is undefinedvar x = 5; // Now x is a Numbervar x = "John"; // Now x is a String
JavaScript Data TypesString • A string is a variable which stores a series of characters like "John Doe". • A string can be any text inside quotes. You can use simple or double quotes: • Example varcarname="Volvo XC60";varcarname='Volvo XC60'; • You can use quotes inside a string, as long as they don't match the quotes surrounding the string: • Example var answer="It's alright";var answer="He is called 'Johnny'";var answer='He is called "Johnny"';
JavaScript Data TypesNumbers • JavaScript has only one type of numbers. Numbers can be written with, or without decimals: • Example var x1=34.00; //Written with decimalsvar x2=34; //Written without decimals • Extra large or extra small numbers can be written with scientific (exponential) notation: • Example var y=123e5;// 12300000var z=123e-5; // 0.00123
JavaScript Data TypesBooleans • Booleans can only have two values: true or false. var x=truevar y=false • Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.
JavaScript Data TypesArrays • The following code creates an Array called cars: var cars=new Array();cars[0]="Saab";cars[1]="Volvo";cars[2]="BMW"; • or (condensed array): var cars=new Array("Saab","Volvo","BMW"); • or (literal array): • Example var cars=["Saab","Volvo","BMW"]; • Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
JavaScript Data TypesObjects • An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas: var person={firstname:"John", lastname:"Doe", id:5566}; • The object (person) in the example above has 3 properties: firstname, lastname, and id.
JavaScript Data TypesObjects • Spaces and line breaks are not important. Your declaration can span multiple lines: var person={firstname : "John",lastname : "Doe",id : 5566}; • You can address the object properties in two ways: • Example name=person.lastname;name=person["lastname"];
JavaScript Data TypesUndefined and Null • Undefined is the value of a variable with no value. • Variables can be emptied by setting the value to null; • Example cars=null;person=null;