JavaScript Netcentric.

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

The Web Warrior Guide to Web Design Technologies
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Week 9 PHP Cookies and Session Introduction to JavaScript.
CSC 330 E-Commerce Teacher Ahmed Mumtaz Mustehsan Ahmed Mumtaz Mustehsan GM-IT CIIT Islamabad GM-IT CIIT Islamabad CIIT Virtual Campus, CIIT COMSATS Institute.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
2440: 211 Interactive Web Programming Expressions & Operators.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
TUTORIAL 10: PROGRAMMING WITH JAVASCRIPT Session 2: What is JavaScript?
CHAPTER 4 Java Script อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
LOGO Introduction to Client-Side Scripting and JavaScript CHAPTER 9 Eastern Mediterranean University School of Computing and Technology Department of Information.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
1 JavaScript
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
JavaScript. JavaScript is the programming language of HTML and the Web. Easy to learn One of the 3 languages of all developers MUST learn: 1. HTML to.
JavaScript Jordan Clark, Jamie Kapilivsky, Taylor Monk, Jessica Torres.
COMP403 Web Design JAVA SCRİPTS Tolgay KARANFİLLER.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 JavaScript in Context. Server-Side Programming.
Pertemuan 5 IT133 Pengembangan Web JavaScript. What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
This is our seminar JavaScript And DOM This is our seminar JavaScript And DOM.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Javascript Web Application Development M. Rehan Abbas Ch, UCP, Lahore.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
Java Script Introduction. Java Script Introduction.
>> Introduction to JavaScript
Introduction to Client-Side Scripting and JavaScript
CHAPTER 10 JAVA SCRIPT.
Web Systems & Technologies
Chapter 6 JavaScript: Introduction to Scripting
PHP 5 Syntax.
My First Web Page document.write("" + Date() + ""); To insert.
Introduction to Scripting
JavaScript Syntax and Semantics
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
PHP Introduction.
JavaScript.
Intro to PHP & Variables
JavaScript an introduction.
Introduction to Client-Side Scripting and JavaScript
Exercises on JavaScript & Revision
Number and String Operations
WEB PROGRAMMING JavaScript.
PHP.
My First Web Page document.write("" + Date() + ""); To insert.
T. Jumana Abu Shmais – AOU - Riyadh
CS105 Introduction to Computer Concepts
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Chapter 2: Introduction to C++.
JavaScript CS 4640 Programming Languages for Web Applications
Tutorial 10: Programming with javascript
Web Programming– UFCFB Lecture 13
CIS 136 Building Mobile Apps
Web Programming and Design
CS105 Introduction to Computer Concepts JavaScript
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

JavaScript Netcentric

Introduction JavaScript is the world's most popular programming language. It is the language for HTML, for the web, for servers, PCs, laptops, tablets, phones, and more. JavaScript and Java are two completely different languages, in both concept and design. Java (invented by Sun) is a more complex programming language in the same category as C. ECMA-262 is the official name of the JavaScript standard. JavaScript was invented by Brendan Eich. It appeared in Netscape (a no longer existing browser) in 1995, and has been adopted by ECMA (a standard association) since 1997.

Introduction JavaScripts in HTML must be inserted between <script> and </script> tags. JavaScripts can be put in the <body> and in the <head> section of an HTML page.

The <script> Tag To insert a JavaScript into an HTML page, use the <script> tag. The <script> and </script> tells where the JavaScript starts and ends. The lines between the <script> and </script> contain the JavaScript: <script> alert("My First JavaScript"); </script>

The <script> Tag <!DOCTYPE html> <html> <body> <p> JavaScript can write directly into the HTML output stream: </p> <script> document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); </script> You can only use <strong>document.write</strong> in the HTML output. If you use it after the document has loaded (e.g. in a function), the whole document will be overwritten. </body> </html>

JavaScript Functions and Events The JavaScript statements, in the example above, are executed while the page loads. More often, we want to execute code when an event occurs, like when the user clicks a button. If we put JavaScript code inside a function, we can call that function when an event occurs.

Location in HTML Document? You can place an unlimited number of scripts in an HTML document. Scripts can be in the <body> or in the <head> section of HTML, and/or in both. It is a common practice to put 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.

External JavaScript Scripts can also be placed in external files. External files often contain code to be used by several different web pages. External JavaScript files have the file extension .js. To use an external script, point to the .js file in the "src" attribute of the <script> tag:

External JavaScript Scripts can also be placed in external files. External files often contain code to be used by several different web pages. External JavaScript files have the file extension .js. To use an external script, point to the .js file in the "src" attribute of the <script> tag:

External JavaScript <!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> <p><strong>Note:</strong> myFunction is stored in an external file called "myScript.js".</p> <script src="myScript.js"></script> </body> </html>

Manipulating HTML Elements To access an HTML element from JavaScript, you can use the document.getElementById(id) method. Use the "id" attribute to identify the HTML element:

Access Element by Id and Change its Content <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p id="demo">My First Paragraph</p> <script> document.getElementById("demo").innerHTML="My First JavaScript"; </script> </body> </html>

Writing to The Document Output The example below writes a <p> element directly into the HTML document output: <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <script> document.write("<p>My First JavaScript</p>"); </script> </body> </html>

Writing to The Document Output Use document.write() only to write directly into the document output. If you execute document.write after the document has finished loading, the entire HTML page will be overwritten e.g. not in the function that will be called after the html page has finished loading.

JavaScript Statements JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the browser what to do. Example: document.getElementById("demo").innerHTML= "Hello Dolly";

Semicolon ; Semicolon separates JavaScript statements. Normally you add a semicolon at the end of each executable statement. Using semicolons also makes it possible to write many statements on one line. Ending statements with semicolon is optional in JavaScript.

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").innerHTML="Hello Dolly"; document.getElementById("myDIV").innerHTML="How are you?";

JavaScript Code 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. A good example of statements grouped together in blocks, are JavaScript functions.

JavaScript Code Blocks This example will run a function that will manipulate two HTML elements: function myFunction() { document.getElementById("demo").innerHTML="Hello Dolly"; document.getElementById("myDIV").innerHTML="How are you?"; }

JavaScript is Case Sensitive Watch your capitalization closely when you write JavaScript statements: A function getElementById is not the same as getElementbyID. A variable named myVariable is not the same as MyVariable.

White Space JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent: var person="Hege"; var person = "Hege";

Break up a Code Line You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("Hello \ World!");

Break up a Code Line However, you cannot break up a code line like this: document.write \ ("Hello World!");

JavaScript Variables As with algebra, JavaScript variables can be used to hold values (x=5) or expressions (z=x+y). Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume). Variable names must begin with a letter

JavaScript Variables Variable names can also begin with $ and _ (but we will not use it) Variable names are case sensitive (y and Y are different variables) Both JavaScript statements and JavaScript variables are case-sensitive.

JavaScript Data Types JavaScript variables can also hold other types of data, like text values (person="John Doe"). In JavaScript a text like "John Doe" is called a string. When you assign a text value to a variable, put double or single quotes around the value.

JavaScript Data Types 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. Example var pi=3.14; var person="John Doe"; var answer='Yes I am!';

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: var carname; After the declaration, the variable is empty (it has no value).

Declaring (Creating) JavaScript Variables To assign a value to the variable, use the equal sign: carname="Volvo"; However, you can also assign a value to the variable when you declare it: var carname="Volvo”;

One Statement, Many Variables You can declare many variables in one statement. Just start the statement with var and separate the variables by comma: var lastname="Doe", age=30, job="carpenter";

One Statement, Many Variables Your declaration can also span multiple lines: var lastname="Doe", age=30, job="carpenter";

Value = undefined In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.

Value = undefined The variable carname will have the value undefined after the execution of the following statement: var carname;

Re-Declaring JavaScript Variables If you re-declare a JavaScript variable, it will not lose its value:. The value of the variable carname will still have the value "Volvo" after the execution of the following two statements: var carname="Volvo"; var carname;

JavaScript Data Types String Number Boolean Array Object Null Undefined

JavaScript Has Dynamic Types This means that the same variable can be used as different types: Example var x; // Now x is undefined var x = 5; // Now x is a Number var x = "John"; // Now x is a String

JavaScript Strings 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 single or double quotes: Example var carname="Volvo XC60"; var carname='Volvo XC60’;

JavaScript Strings 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 Numbers JavaScript has only one type of numbers. Numbers can be written with, or without decimals: Example var x1=34.00; // Written with decimals var x2=34; // Written without decimals

JavaScript Numbers Extra large or extra small numbers can be written with scientific (exponential) notation: Example var y=123e5; // 12300000 var z=123e-5; // 0.00123

JavaScript Booleans Booleans can only have two values: true or false. var x=true; var y=false;

JavaScript Arrays 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");

JavaScript Arrays or (literal array): var cars=["Saab","Volvo","BMW"];

JavaScript Objects 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};

JavaScript Objects The object (person) in the example above has 3 properties: firstname, lastname, and id. Spaces and line breaks are not important. Your declaration can span multiple lines: var person={ firstname : "John", lastname : "Doe", id : 5566 };

JavaScript Objects You can address the object properties in two ways: Example name=person.lastname; name=person["lastname"];

Undefined and Null Undefined is the value of a variable with no value. Variables can be emptied by setting the value to null; cars=null; person=null;

Declaring Variables as Objects When a variable is declared with the keyword "new", the variable is declared as an object: var name = new String; var x = new Number; var y = new Boolean;

JavaScript Objects Objects are just data, with properties and methods. Properties are values associated with objects. Methods are actions that objects can perform. car.name = Fiat car.model = 500 car.weight = 850kg car.color = white car.start() car.drive() car.brake()

JavaScript Objects You create a JavaScript String object when you declare a string variable like this: var txt = new String("Hello World"); You can also create your own objects. This example creates an object called "person", and adds four properties to it: person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue";

Accessing Object Properties The syntax for accessing the property of an object is: objectName.propertyName e.g var message="Hello World!"; var x=message.length;

Accessing Object Methods You can call a method with the following syntax: objectName.methodName() This example uses the toUpperCase() method of the String object, to convert a text to uppercase: var message="Hello world!"; var x=message.toUpperCase();

JavaScript Functions A function is written as a code block (inside curly { } braces), preceded by the function keyword: function functionname() { some code to be executed }

JavaScript Functions The code inside the function will be executed when "someone" calls the function. The function can be called directly when an event occurs (like when a user clicks a button), and it can be called from "anywhere" by JavaScript 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 (,) myFunction(argument1,argument2)

Calling a Function with Arguments Declare the argument, as variables, when you declare the function: function myFunction(var1,var2) { some code }

Calling a Function with Arguments e.g. <button onclick="myFunction('Harry Potter','Wizard')">Try it</button> <script> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script>

Functions With a Return Value Sometimes you want your function to return a value back to where the call was made. This is possible by using the return statement. When using the return statement, the function will stop executing, and return the specified value. Syntax function myFunction() { var x=5; return x; }

Functions With a Return Value 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 }

Local JavaScript Variables A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from 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.

Global JavaScript Variables Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.

The Lifetime of JavaScript Variables The lifetime of JavaScript variables starts when they are declared. Local variables are deleted when the function is completed. Global variables are deleted when you close the page.

Assigning Values to Undeclared JavaScript Variables If you assign a value to a variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable. carname="Volvo"; will declare the variable carname as a global variable, even if it is executed inside a function.

JavaScript Arithmetic Operators Y=5; Operator Description Example Result of x Result of y + Addition x=y+2 7 5 - Subtraction x=y-2 3 * Multiplication x=y*2 10 / Division x=y/2 2.5 % Modulus (division remainder) x=y%2 1 ++ Increment x=++y 6 x=y++ -- Decrement x=--y 4 x=y--

JavaScript Assignment Operators Example Same As Result = x=y   x=5 += x+=y x=x+y x=15 -= x-=y x=x-y *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0 X=10; Y=5;

JavaScript Comparison Operators Description Comparing Returns == equal to x==8 false x==5 true === exactly equal to (equal value and equal type) x==="5" x===5 !=  not equal x!=8 !==  not equal (different value or different type) x!=="5" x!==5 >  greater than x>8 <  less than x<8 >=  greater than or equal to x>=8 <=  less than or equal to x<=8 X=5;

JavaScript Logical Operators Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true X=6; Y=3;

JavaScript Conditional Operators JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2  e.g. If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise the value of voteable will be "Old enough": voteable=(age<18)?"Too young":"Old enough";

Adding Strings and Numbers 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; The result of x,y, and z will be: 10 55 Hello5

Conditional Statements In JavaScript we have the following conditional statements: if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false if...else if....else statement - use this statement to select one of many blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed

If Statement Use the if statement to execute some code only if a specified condition is true if (time<20)   {   x="Good day";   }pecified condition is true.

If...else Statement Use the if....else statement to execute some code if a condition is true and another code if the condition is not true. if (time<20)   {   x="Good day";   } else   {   x="Good evening";   }

If...else if...else Statement Use the if....else if...else statement to select one of several blocks of code to be executed. if (time<10)   {   x="Good morning";   } else if (time<20)   {   x="Good day";   } else   {   x="Good evening";   }

The JavaScript Switch Statement Use the switch statement to select one of many blocks of code to be executed.

The JavaScript Switch Statement var day=new Date().getDay(); switch (day) { case 0:   x="Today is Sunday";   break; case 1:   x="Today is Monday";   break; }

The default Keyword Use the default keyword to specify what to do if there is no match: var day=new Date().getDay(); switch (day) { case 0:   x="Today is Sunday";   break; case 1:   x="Today is Monday";   break; default: x="Looking forward to the Weekend"; }

JavaScript Loops Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this is the case when working with arrays: for (var i=0;i<cars.length;i++) {  document.write(cars[i] + "<br>"); }

Try Yourself For Loop While Loop Break and Continue Statements

JavaScript Errors - Throw and Try to Catch The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors.

JavaScript Errors - Throw and Try to Catch When the JavaScript engine is executing JavaScript code, different errors can occur: It can be syntax errors, typically coding errors or typos made by the programmer. It can be misspelled or missing features in the language (maybe due to browser differences). It can be errors due to wrong input, from a user, or from an Internet server. And, of course, it can be many other unforeseeable things.

JavaScript Errors - Throw and Try to Catch try   {   //Run some code here   } catch(err)   {   //Handle errors here   }

JavaScript Form Validation JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be: has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?

JavaScript Form Validation Examples: See examples for form and email validation