Sei sulla pagina 1di 34

INTRODUCTION TO HTML

Tim Berners-Lee at Cern, Switzerland designed the original HTML document type in 1990. HTML can be used to display any type of document that is available on the web. HTML is a versatile language and can be used on any platform or desktop. Being platform independent, documents written in HTML can be viewed on any platform. The language used to develop web pages is called HTML. HTML languages interpreted by a browser. Web pages are also called as HTML documents. HTML is a special set of codes that can be embedded in text to add linking information and formatting. HTML is specified as TAGs in an HTML document that is the web page.

HTML TAGS
HTML tags are instructions that are embedded directly into the text of the document. An HTML tag is a signal to a browser that it should do something other than just throw text up on the screen. By convention all HTML tags being with an open angle bracket(<) and end with a close angle bracket(>). HTML tags can be of two types: 1) Paired Tag: A tag is said to be a paired tag if it along with companion tag. e.g. The <B> tag is a paired tag. The <B> tag with its companion tag </B> causes the text contained between them to be rendered in bold. The effect of other paired tags is applied only to the text they contain. 2) Singular Tag: The second type of tag is the singular or stand-alone tag. A stand-alone tag doesnt have a companion tag. e.g </BR> tag insert a line break. Structure in the head section of your HTML file: <html> <head><title> ... </title></head> <body> Body part</body> </html>

Tags in the Head Section

<html> ... </html> The <html> tag must be the VERY FIRST tag that appears in any HTML file. <html> tells the Web browser that this is the beginning of an HTML document and the </html> tag tells the browser that the HTML file is finished. The tags with slash "/" respresent a closing tag. <head> ... </head> The <head> and </head> tags defines that part of the document containing information about the page. This section includes the TITLE of the document. <title> ... </title> This tag surrounds the TITLE of your document. Note: The TITLE appears at the top of your browser window. For example, look at the top of this page.

Tags in the Body Section

This is the section where your creativity will distinguish you from other homepages around the Web. Experiment with the many tags that will be introduced to you and have fun. <body> ... </body> The <body> tag usually comes immediately after the </head> tag that ended your HEAD section. The </body> tag comes before the </html> tag at the end of the document. <p> This tag signals the end of one paragraph and the beginning of the next. There is supposed to be a closing tag </p> tag. One thing to keep in mind is that web browsers cannot indent the first word of a paragraph, so this tag leaves a blank space between two paragraphs; however,
2

multiple <p> tags will NOT result in multiple blank lines. Align is the main attribute of an <p> tag. This attribute is having 3 values such as Left, Right and Center. <br> This tag represents a line break. It also does not have a closing tag. <hr> This the horizontal rule tag. It instructs the browser to insert a paragraph break into the content with a line separating the paragraphs. The browser will automatically adjust the line to fill the width of the display window. A default grey line is created with just the <hr> tag. To get a little fancier, you can make the line solid black with the tag <hr NOSHADE>. A SIZE andWIDTH option can be added to the <hr NOSHADE> tag. The thickness of a line is specified in this format SIZE="x" as in <hr SIZE="x">. The width is represented by WIDTH="xx%" as in <HR WIDTH="xx%">. <address> ... </address> The address tag is used for signatures, addresses, and other authorship information usually appearing at the top or bottom of the page. The text between the address tags is shown on-line in italics. <address>Prepared by: Brenda Karp</address>

Tags for Lists

There are three types of lists that can be done with HTML: unordered lists, ordered lists, and definition lists. <ul> ... </ul> The ul tag specifies an unordered type list. By default, the list items are preceded by a round bullet. With the TYPE attribute you can specify what type of bullet you want. Values for this attribute are "circle", "square", and "disc" and are incorporated in the ul tag in this
3

fashion: <ul type="square">. Within the ul tags, each item in a list is preceded with the list item tag, <li>. For example, if I wanted to list oranges, apples, and pears on-line, your html file would look like this:

<ul> <li>oranges</li> <li>apples</li> <li>pears</li> </ul> Would look like:


oranges apples pears

<ol> ... </ol> The ol tags represent the ordered type lists. It is set up in your html file like the ul tags. By default, the list is ordered by numbers; however, you can change this by using the TYPE attribute. Letters can be uppercase [type="A"], lowercase [type="a"], small roman numerals [type="i"], or large roman numerals [type="I"]. An ordered list with lowercase letters would look like this: <OL type="a"> <dl> ... </dl> The definition list is set up a little differently than the ordered and unordered lists. Instead of using a list item tag, <li>, to separate the list items, the <dt> or the <dd> tags can be used. The <dt> or definition term tag does NOT indent the item. The <dd> or definition description tag indents the item. For example, if I wanted to use the fruit items list from earlier, it would look like this:

<dl> <dt>My favorite fruits</dt> <dd>oranges</dd> <dd>apples</dd> <dd>pears</dd> </dl> Would look like:

My favorite fruits oranges apples pears

"My favorite fruits" would not be indented whereas oranges, apples, and pears would be indented. In setting up for this tutorial, I used the <dl> and <dd> tags.

Linking to...

<a href="filename"> </a> This is the tag in HTML that creates a hyperlink to another Web page. The a is known as an anchor and it has one prime attribute, href or Hypertext REFerence. The href attribute has one value and that is the URL or Uniform Resource Locator. Whatever comes before the </a> tag, be it text or an image, is the blue clickable part that takes you to your destination, or the URL specified; If you are going to create a link to a file in another directory, you need to specify where the file is located by doing one of the following. There are four general types of links distinguished by the location of the file you are linking to: 1. Specifying a URL for a file in the same directory: <a href="filename.html">Text you want user to see</a> The previous code produces a link that appears as: Text you want user to see 2. Specifying a URL for a file in a subdirectory: <a href="subdir/filename.html">Text you want user to see</a> 3. Specifying a URL elsewhere on the same server: <a href="/visitor/directions/">How to get here</a> Note: the URL above links to a file "index.html", but the default behavior for the server when no file is indicated is to open "index.html" if it exists. If no file "index.html" exists in that directory then a list of files in that directory is returned. The previous code produces a link that appears as: How to get here 4. Specifying a URL for a file on another web server: <a href="http://www.theregister.co.uk//peruvian_opensou_nightmare/"> M$ in Peruvian open-source nightmare</a>

The previous code produces a link that appears as: nightmare from The Register.

M$ in Peruvian open-source

The a href tag is also used to link to postscript and pdf files: Linking to a postscript file: <a href="../nlpap.ps"/>Nonlinear Model Reduction Using Hankel-norm approximations</a>

Tags for Images

Here are a few things to keep in mind when using graphics on your WWW pages. 1. Graphics take time to load. 2. As you start using graphics on your Web pages, you may see a graphic that you want to use on someone else's page. Welcome to the ambiguous world of Internet copyright law. If you do decide to use someone else's, chances are that you will not get in trouble for using the graphic as long as you use it respectfully. However, there are sites on the Web that purposely house icons, bullets, and inline images for public use. 3. Attributes for the IMG tag include: SRC - The source attribute is a must for this tag. Its value is the URL of the file containing the image that you are placing on-line. ALIGN - "top", "middle", "bottom", "center", "right", and "left" are the values for this attribute. The "right" and "left" values allow for text to be wrapped around the image. ALT - This attribute is for those viewers who have browsers that have no graphics capability. With this attribute you need to specify a text string that can be displayed. BORDER - This attribute allows you to place a border around your image. The value of this attribute is "n", where n stands for a number that represents the thickness of the border, the default = "0" There are two ways an image file can be displayed, inline or as a link to a Web page. To create an inline image use the following tag in this fashion:
6

<img src="filename.gif" alt="image description"> You can also use an image as a link to another Web page: <a href="http://che.www.ecn.purdue/"><img src="images/griffin.gif" alt="link uses an image of a griffin"></a>

Character Entities

&nbsp;

Non-break space. This entity allows you to put spaces into the display. Normal spaces like " " are collapsed to a single space by the browser. Using this entity allows you to put in as many spaces as you like. Also useful for blank cells in tables and (used as <p> &nbsp; </p> ) for extra blank lines.

&lt; and &gt;

Less than (<) and greater than (>). These characters define tags in HTML, and thus the browser interprets the actual "<" and ">" symbols as something other than the literal symbols. Use the entity tags to display these characters.

&amp;

Ampersand (&). As with "less than" and "greater than", the ampersand is not interpreted literally by browser, and so it must be written as an entity to get it to display properly.

&plusmn; &copy; &reg;

Plus-or-minus (), Copywrite() and registered trademark ().

&cent; &pound; &euro; &yen; &curren; &alpha; &beta; &gamma; &delta; &epsilon; &theta; &kappa; &lambda; &mu; &pi; &rho; &sigma; &phi; &chi; &omega;

Cent(), Pound (), Euro(), Yen (), General currency (). Some small Greek letters: alpha() beta () gamma () delta() epsilon () theta () kappa () lambda () mu () pi () rho () sigma () phi () chi () omega () .

&Gamma; &Delta; &Theta; &Lambda; &Xi; &Pi; &Sigma; &Phi; &Psi; &Omega;

Some capital Greek letters: Gamma () Delta () Theta () Lambda () Xi () Pi () Sigma () Phi () Psi () Omega ()

Frameset Tag

HTML frames allow authors to present documents in multiple views, which may be independent windows or sub windows. Multiple views offer designers a way to keep certain information visible, while other views are scrolled or replaced. For example, within the same window, one frame might display a static banner, a second a navigation menu, and a third the main document that can be scrolled through or replaced by navigating in the second frame. The splitting of a browser screen into frames is accomplished with the <FRAMESET> and </FRAMESET> tags embedded into the HTML document. The <FRAMESET> screen has to be divided into rows or columns. Rows: This attribute is used to divide the screen into multiple rows. It can be set equal to a list of values. Depending on the required size of each row. The values can be:

A number of pixels Expressed as a percentage of the screen resolution. The symbol *, which indicates the remaining space. Cols : This attribute is used to divide the screen into multiple columns. It can be set

equal to a list of values. Depending on the required size of each column. The values can be:

A number of pixels Expressed as a percentage of the screen resolution. The symbol *, which indicates the remaining space.

e.g. <frameset rows=33%,33%,33%> <frameset cols=50%,50%>


8

</frameset> <frameset cols=50%,50%> </frameset> </frameset>

Frame Tag

Once the browser screen is divided into rows (horizontal sections), and columns (vertical sections), each unique section defined can be loaded with different HTML documents. This is achieved by using the <FRAME> tag, which takes in the following attributes: SRC=url : indicates the URL of the document to be loaded into the frame. MARGINHEIGHT=n : specifies the amount of white space to be left at the top and bottom of the frame. MARGINWIDTH=n : specifies the amount of white space to be left along the sides of the frame. NAME=name: gives the frame a unique name so it can be targeted by other documents. The name given must begin with an alphanumeric character. NORESIZE : Disables the frames resizing capability. SCROLLING : controls the appearance of horizontal and vertical scrollbars in a frame. This takes the values yes/no/auto. HREF: the attribute via which the HTML file name is specified is the HREF attribute which is a part of the <A></A> tag. TARGET: the attribute via which the frame name is specified is the TARGET attribute, which is a part of the <A></A> tag. e.g. <frameset rows="30%,*">
9

<frame src="TableExample.html"></frame> <frameset cols="50%,*"> <frame src="TableExample.html"></frame> <frame scr="TableExample.html"></frame> </frameset> </frameset>

Overview of JavaScript
JavaScript is most commonly used as a client side scripting language. This means that JavaScript code is written into an HTML page. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it. JavaScript was developed by Brendan Eich, then working at Netscape, as a client side scripting language (even though there's no fundamental reason why it can't be used in a server side environment). JavaScript was released by Netscape and Sun Microsystems in 1995. However, JavaScript is not the same thing as Java. What is JavaScript It is a programming language. It is an interpreted language. It is object-based programming. It is widely used and supported It is accessible to the beginner. Uses of JavaScript Use it to add multimedia elements With JavaScript you can show, hide, change, resize images, and create image rollovers. You can create scrolling text across the status bar. Create pages dynamically Based on the user's choices, the date, or other external data, JavaScript can produce pages that are customized to the user.

10

Interact with the user It can do some processing of forms and can validate user input when the user submits the form. Writing JavaScript JavaScript code is typically embedded in the HTML, to be interpreted and run by the client's browser. Here are some tips to remember when writing JavaScript commands. JavaScript code is case sensitive White space between words and tabs are ignored Line breaks are ignored except within a statement JavaScript statements end with a semi- colon ; The SCRIPT Tag The <SCRIPT> tag alerts a browser that JavaScript code follows. It is typically embedded in the HTML. <SCRIPT language = "JavaScript"> statements </SCRIPT> SCRIPT Example Open "script_tag.html" in a browser. View the Source Put the cursor after <! Enter code below and enter the following: <SCRIPT language = "JavaScript"> alert("Welcome to the script tag test page.")

11

</SCRIPT> 5 Save the changes by choosing Save from the File menu. Then Refresh the browser by clicking the Refresh or Reload button. Implementing JavaScript There are three ways to add JavaScript commands to your Web Pages. Embedding code Inline code External file

Primitives of JavaScript

Numbers - are values that can be processed and calculated. You don't enclose them in quotation marks. The numbers can be either positive or negative.

Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string literally; it doesn't process it. You'll use strings for text you want displayed or values you want passed along.

Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified criteria.

Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is the absence of any value. Integers

In JavaScript, you can express integers in 3 different Bases:


base 10, base 8 (octal), and base 16 (hexadecimal).


12

Base 8 numbers can have digits only up to 7, so a decimal value of 18 would be an octal value of 22. Similarly, hexadecimal allows digits up to F, where A is equivalent to decimal 10 and F is 15. So, a decimal value of 18 would be 12 in hexadecimal notation.

Converting Numbers to Different Bases Table

In order to distinguish between these three bases, JavaScript uses the following notation. Specifying bases in JavaScript NUMBER SYSTEM Decimal (base 10) Octal (base 8) NOTATION A normal integer without a leading 0 (zero) (ie, 752) An integer with a leading 0 (zero) (ie, 056)

Hexadecimal (base 16) An integer with a leading 0x or 0X (ie, 0x5F or 0XC72)

Floating Point Values Floating point values can include a fractional component. A floating-point literal includes a decimal integer plus either a decimal point or a fraction expressed as another decimal number or an expression indicator and a type suffix

7.2945 -34.2 2e3 means 2 x 103 => 2000 2E-3 means 2 x 10-3 => .002

Floating point literals must, at a minimum, include a decimal integer and either the decimal point or the exponent indicator ("e" or "E"). As with integers, floating point values can be positive or negative.

13

Strings Technically, a string literal contains zero or more characters enclosed, as you know, in single or double quotes:

"Hello!" 245 "" // This example is called the empty string.

NOTE: the empty string is distinct from the null value in JavaScript. NOTE: Strings are different from other data types in JavaScript. Strings are actually Objects. This will be covered later on. Boolean A Boolean value is either true or false. Note: Unlike Java, C and other languages, in JavaScript Boolean values can only be represented with true and false. Values of 1 and 0 are not considered Boolean values in JavaScript. Null Value The null value is a special value in JavaScript. The null value represents just that Nothing. If you try to reference a variable that isnt defined and therefore has no value, the value returned is the null value. Likewise, with the prompt() dialog box, if the user selects the Cancel button, a null is returned. (example) NOTE: This is distinct from a value of zero or an empty string where this is an "actual" value. The null value is indicated in JavaScript by the term null. NaN (Not a Number) In addition to these values, some functions return a special value called NaN which means that the value is not a number, parseInt() and parseFloat() are an examples of functions that return NaN when the argument passed to them cannot be evaluated to a number.
14

NOTE: Values can be tested to see if they are NaN by using the isNaN() function which returns true or false based on the nature of the argument passed to the function.

Date and Time in JavaScript


The Date object is used to work with dates and times. Date objects are created with new Date(). There are four ways of instantiating a date: var d = new Date(); var d = new Date(milliseconds); var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds); Date Object Properties: Property constructor Description Returns the function that created the Date object's prototype

prototype

Allows you to add properties and methods to an object. The prototype constructor allows you to add new properties and methods to the Date() object. When constructing a property, ALL date objects will be given the property, and it's value, as default.When constructing a method, ALL date objects will have this method available.

Example of Constructor: <html> <body> <p id="demo">Click the button to create a Date object, then display it's constructor</p> <button onclick="myFunction()">Try it</button> <script> function myFunction(){

15

var d = new Date(); var x=document.getElementById("demo"); x.innerHTML=d.constructor; } </script> </body> </html> Output: function Date() { [native code] } Example of Prototype: Make a new date method that gives the date object a month-name property called myProp. Date Object Methods:

Method getDate()

Description Returns the day of the month (from 1-31)

getDay()

Returns the day of the week (from 0-6)

getFullYear()

Returns the year (four digits)

getHours()

Returns the hour (from 0-23)

getMilliseconds()

Returns the milliseconds (from 0-999)

getMinutes()

Returns the minutes (from 0-59)

getMonth()

Returns the month (from 0-11)

16

getSeconds()

Returns the seconds (from 0-59)

getTime()

Returns the number of milliseconds since midnight Jan 1, 1970

setDate()

Sets the day of the month of a date object

setFullYear()

Sets the year (four digits) of a date object

setHours()

Sets the hour of a date object

setMilliseconds()

Sets the milliseconds of a date object

setMinutes()

Set the minutes of a date object

setMonth()

Sets the month of a date object

setSeconds()

Sets the seconds of a date object

setTime()

Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970

toDateString()

Converts the date portion of a Date object into a readable string

toString()

Converts a Date object to a string

Operations and Expression in JavaScript


Expressions : An expression is any valid set of literals, variables, operators and expresions that evaluates to a single value. This value can be a number, a string or a logical value.

17

Operators : JavaScript has assignment, comparision, arithmetic, bitwise, logical, string and special operators. There are binary and unary operations. Binary operations require two operands and one operator, and the order is: operand1 operator operand2 Unary operations require a single operand, before or after the operator operator operand or operand operator

JavaScript has also one ternary operation: the conditional operation, and it requires three operands. Assignment Operators : An assignment operator assigns its left operand with the value of the right operand. The assignement operator is equal ('='). The shorthand operators exist for standard operations, assigning a new value to a variable based in its old value. Here's a table representing the shorthand formats available in JavaScript. Shorthand Operator x += y x -= y x *= y x /= y x %= y x <<= y

Meaning

Description

x = x + y Adds x with y and sets x with the result x=xy x=x*y x=x/y Subtracts y to x and sets x with the result Multiplies x by y and sets x with the result Divides x by y and sets x with the result

x = x % y Sets x with the integer reminder of dividing x by y x = x << y x = x >> y Shifts x in binary representation y bits to left, shifting in zeros from right, and sets x with the result Shifts x in binary representation y bits to the right, discarding bits shifted off, and sets x with the result

x >>= y

18

x >>>= y

x = x >>> y

Shifts x in binary representation y bits to the right, discarding bits shifted off, shifting in zeros from the left, and sets x with the result

x &= y x ^= y x |= y

x = x & y Bitwise AND between x and y and sets x with the result x=x^y x=x|y Bitwise XOR between x and y and sets x with the result Bitwise OR between x and y and sets x with the result

Comparision Operator: This operator compares two operands and return a logical value based on the comparision result. The operands can be numerical or strings: when using strings, the comparision is based on the lexicographical ordering. There are only two values possible: true or false. The following table describes these operators: For the examples consider x = 4 and y = 5 Operator Description == Equal. Returns true if both operands are equal Examples x == y returns false x != y returns true x > y returns false

!=

Not equal. Returns true if both operands are not equal Greater than. Returns true if the left operand is greater than the right operand

>

>=

Greater or equal than. Returns true if the left operand is greater or x >= y returns equal than the right operand Less than. Return true if left operand is les than right operand Less or equal than. Returns true if left operand is less or equal than right operand. false x < y returns true x <= y returns true

<

<=

19

Arithmetic Operators : These oprators take numerical values as their operands and return a single numerical value. The next table describes them: For the example consider a=12 and b=7 Operator Description +, -, *, / Standard arithmetic operators % Modulus. Returns the integer reminder of dividing a by b Increments its unique operand by one. If it is used as ++ prefix, the operand value and the return value are incremented. If it is used as a postfix, returns the value of its operand before adding one Examples b-a returns -5 a % b returns 5 25 % a returns 1 a++ and ++a set a to 13, but in the first case it returns 12 and in the second case it returns 13

Decrements its unique operand by one. If it is used as b-- and b++ set b to 6, but -prefix, the operand value and the return value are decremented. If it is used as a postfix, returns the value of its operand before subtracing one Negation. Returns the negation of its operand in the first case it returns 5 and in the second case it returns 6 -a returns -12

Bitwise Operators : These operators work with the binary representation of each of its operands, but they always return standard JavaScript numerical values. For the example consider a=30 (11110), b=87(1010111) and c=3 Operator Description & AND.Returns a one in each bit position, if bits of both operands are ones. Returns a zero for all the other cases OR.Returns a zero in each bit position, if bits of both operands are zeros. Returns a one for all the other cases
20

Examples a & b returns 22 (10110) a | b returns 95 (1011111)

XOR. Returns a one in each bit position if bits of both operands are different. Returns a zero for all the other cases LEFT SHIFT. Shifts the first operand in binary representation by

a ^ b returns 73 (1001001) a << c returns 240 (11110000)

<<

the number of bits refered by the second operand to the left, shifting in zeros from the right. SIGN-PROPAGATING RIGHT SHIFT. Shifts the first operand

>>

in binary representation by the number of bits refered by the second operand to the right, discarding bits shifted off. ZERO-FILL RIGHT SHIFT. Shifts the first operand in binary

b >> c returns 10 (1010)

>>>

representation by the number of bits refered by the second

b >>> c returns

operand to the right, discarding the bits shifted off and shifting in 10 (1010) zeros from the left.

String Operators : Comparison operators and the concatenation operator (+) can be used on string values. The concatenation operator returns a string which is the result of the union between the two operands (at least one of them must be a string.) Some Special Operators : The conditional operator is the only operator in JavaScript that takes three operands. The syntax for this operator is: (condition) ? val1: val2 If condition is true, the operator has the value of val1. Otherwise it has the value of val2. Here's an example fot this operator: status = (age>=18) ? "adult" : "minor" The comma operator (,) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. Suppose you want to create a loop using the comma operator:
21

for (var i=0, j=5; i<=5; i++, j-=2) document.writeln("("+i+","+j+")") Output: (0,5) (1,3) (2,1) (3,-1) (4,-3) (5,-5)

Functions
A function is written as a code block (inside curly { } braces), preceded by the function keyword: function functionname() { some code to be executed } 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. 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) Declare the argument, as variables, when you declare the function:
22

function myFunction(var1,var2) { some code } The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc. Example: <html> <body> <p>Click the button to call a function with arguments</p> <button onclick="myFunction('Harry Potter','Wizard')">Try it</button> <script> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script> </body> </html> Output: The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.

23

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; } The function above will return the value 5. Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will continue executing code, where the function-call was made from. 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 return value without storing it as a variable: document.getElementById("demo").innerHTML=myFunction(); The innerHTML of the "demo" element will be 5, which is what the function "myFunction()" returns. You can make a return value based on arguments passed into the function:

24

Example: Calculate the product of two numbers, and return the result: <html> <body> <p>This example calls a function which performs a calculation, and returns the result:</p> <p id="demo"></p> <script> function myFunction(a,b) { return a*b; } document.getElementById("demo").innerHTML=myFunction(4,3); </script> </body> </html> Output: This example calls a function which performs a calculation, and returns the result:
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.

25

Array
An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: var car1="Saab"; var car2="Volvo"; var car3="BMW"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Create an Array An array can be created in three ways. The following code creates an Array object called myCars: 1: Regular: var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; 2: Condensed: var myCars=new Array("Saab","Volvo","BMW"); 3: Literal: var myCars=["Saab","Volvo","BMW"];

26

Access an Array You refer to an element in an array by referring to the index number. This statement access the value of the first element in myCars: var name=myCars[0]; This statement modifies the first element in myCars: myCars[0]="Opel"; All JavaScript variables are objects. Array elements are objects. Functions are objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array: myArray[0]=Date.now; myArray[1]=myFunction; myArray[2]=myCars;

Create New Methods Prototype is a global constructor in JavaScript. It can construct new properties and methods for any JavaScript Objects. Example: Make a new Array method. Array.prototype.ucase=function() { for (i=0;i<this.length;i++) {this[i]=this[i].toUpperCase();} } The example above makes a new array method that transforms array values into upper case. Source Code: <!DOCTYPE html> <html>
27

<body> <p id="demo">Click the button to create an array, call the new ucase() method, and display the result.</p> <button onclick="myFunction()">Try it</button> <script> Array.prototype.myUcase=function() { for (i=0;i<this.length;i++) { this[i]=this[i].toUpperCase(); } } function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.myUcase(); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html> Output: BANANA,ORANGE,APPLE,MANGO

28

Array Methods 1.Join two arrays - concat() 2.Join three arrays - concat() 3.Join all elements of an array into a string - join() 4.Remove the last element of an array - pop() 5.Add new elements to the end of an array - push() 6.Reverse the order of the elements in an array - reverse() 7.Remove the first element of an array - shift() 8.Select elements from an array - slice() 9.Sort an array (alphabetically and ascending) - sort() 10.Sort numbers (numerically and ascending) - sort() 11.Sort numbers (numerically and descending) - sort() 12.Add an element to position 2 in an array - splice() 13.Convert an array to a string - toString() 14.Add new elements to the beginning of an array - unshift() Example of POP(): <!DOCTYPE html> <html> <body> <p id="demo">Click the button to remove the last array element.</p> <button onclick="myFunction()">Try it</button> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.pop(); var x=document.getElementById("demo"); x.innerHTML=fruits;
29

} </script> </body> </html> Output: Banana,Orange,Apple

Creating JavaScript Objects


With JavaScript you can define and create your own objects. There are 2 different ways to create a new object:

1. Define and create a direct instance of an object. 2. Use a function to define an object, then create new object instances.

Creating a Direct Instance: This example creates a new instance of an object, and adds four properties to it: Example: person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue";

Alternative syntax (using object literals): Example: person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}; Using an Object Constructor: This example uses a function to construct the object: Example: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age;
30

this.eyecolor=eyecolor; }

The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand. Creating JavaScript Object Instances: Once you have a object constructor, you can create new instances of the object, like this: var myFather=new person("John","Doe",50,"blue"); var myMother=new person("Sally","Rally",48,"green");

Adding Properties to JavaScript Objects: You can add new properties to an existing object by simply giving it a value. Assume that the personObj already exists - you can give it new properties named firstname, lastname, age, and eyecolor as follows: person.firstname="John"; person.lastname="Doe"; person.age=30; person.eyecolor="blue"; x=person.firstname; Creating JavaScript Objects: With JavaScript you can define and create your own objects. There are 2 different ways to create a new object:

1. Define and create a direct instance of an object. 2. Use a function to define an object, then create new object instances.

Creating a Direct Instance: This example creates a new instance of an object, and adds four properties to it: Example: person=new Object(); person.firstname="John";
31

person.lastname="Doe"; person.age=50; person.eyecolor="blue";

Alternative syntax (using object literals): Example: person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

Using an Object Constructor: This example uses a function to construct the object: Example: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand. Creating JavaScript Object Instances: Once you have a object constructor, you can create new instances of the object, like this: var myFather=new person("John","Doe",50,"blue"); var myMother=new person("Sally","Rally",48,"green");

Adding Properties to JavaScript Objects: You can add new properties to an existing object by simply giving it a value. Assume that the personObj already exists - you can give it new properties named firstname, lastname, age, and eyecolor as follows: person.firstname="John"; person.lastname="Doe"; person.age=30;
32

person.eyecolor="blue"; x=person.firstname; The value of x, after execution of the code above will be: John Adding Methods to JavaScript Objects: Methods are just functions attached to objects. Defining methods to an object is done inside the constructor function: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.changeName=changeName;

function changeName(name) { this.lastname=name; } } The changeName() function assigns the value of name to the person's lastname property. myMother.changeName("Doe");

Adding Methods to JavaScript Objects: Methods are just functions attached to objects. Defining methods to an object is done inside the constructor function: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age;
33

this.eyecolor=eyecolor;

this.changeName=changeName; function changeName(name) { this.lastname=name; } } The changeName() function assigns the value of name to the person's lastname property. myMother.changeName("Doe");

34

Potrebbero piacerti anche