Sie sind auf Seite 1von 15

FUNCTIONS

A function groups together a set of statements under a named sub routine. This allows you to conveniently call the function whenever its action is required. Functions are the most fundamental building blocks of most JavaScript programs. Functions are blocks statements under a named subroutine. Syntax: Function functionname (arguments) { statements } Before you call a function you must first create it. We can break down the use of function into two logical categories:1. Defining functions. 2. Calling functions. The function definition is a statement which describes the function: it is name-any values (arguments) which it accepts in coming and the statements of which the function is comprised
Syntax
function functionname(var1,var2,...,varX) { some code }

where; thefunctionname=identifier which is a unique name for the function. Statements=It is a list of statements that you want to be executed when you call a function. N.B a function does not necessarily require arguments in which case you only need to write out the parenthesis. I.e. functionname(). Generally it is best to define functions for a page in the head portion of a document. Since the head is loaded first, this guarantees that the functions are loaded before the user has a chance to do anything that might call a function. Alternatively some programmers place all their functions in a separate file and includes them in a page using the src attribute of the script tag. Either way the key is to load function definitions before any code is executed. e.g. a simple function which outputs an argument to a webpage as a bold and link message. Function boldblink(message) { Document.write(<blink><strong>+message+</strong></blink>;

}
Example 2:

<html> <head> <script type=text/JavaScript> Function message() { Alert(hello word) } </head> <body> <form> <input type=button value=click me onclick=message()/> </form></body><html>

JAVASCRIPT OBJECTS
Properties- characteristics of an object e.g. document.bgcolor=blue; Methods-functions associated with a particular object

CREATING OBJECTS There are two main ways of creating objects:1. Creating a direct instance of an object 2. Creating a prototype of an object 1.Creating a direct instance of an object It simply means creating a new single object. E.g. Mybook=new object();

Mybook.title= the river between; Mybook.author= Ngugi waThiongo; Mybook.publisher= longhorn publisher; Mybook.isbn= 2478191-890-9900; Mybook.yearofpublication= 1960; Creating a prototype of an object Sometimes you will want to create a template or a prototype of an object. This does not actually create an instance of an object but defines the structure of an object. In the future, then you can quickly stamp out a particular instance of an object. Supposing instead of mybook, you created a prototype named book. This object could be then be a template for a particular book object. First create a function that defines the book structure. Function book(title, author, publisher, isbn, year of publisher) { This.title= title; This.author= author; This.publisher= publisher; This.isbn=isbn; This.yearofpublication= yearofpublication; } Yourbook= new book(my life in crime, john kiriamiti, 97378429, 1960);

BROWSER OBJECTS DOM-document object model It is often referred to as the DOM. This object model is a hierarchy of all objects built in to JavaScript. Most of these objects are directly related to the characteristics of the web page or the browser. The reason we qualify the term built in is because the DOM is technically separate from JavaScript itself i.e. the JavaScript language specification is standardized by ECMA, does not actually specify the nature or the specifics of the DOM. In summary then what we refer as JavaScript is actually made up of both JavaScript the language and the DOM, or the object model which JavaScript can acess.

Properties of objects While an object provides an easy way to handle various facets to handle the browser or documents, properties are the data values for these objects. In JavaScript objects are equivalent to HTML tags and the object properties are equivalent to the HTML attributes. Accessing the properties of a given object, this is done by specifying the object name followed by a period (.) and then the desired property. E.g. document.color= red which accesses the current document color and sets it to red. Methods of an object Like any other programming language, JavaScript support functions. If a function is associated with an object it is called a method and can manipulate the properties of an object directly. The basic syntax of a method is objectName.methodName () Any arguments required for method are passed between the parentheses just like a normal function call. E.g. document.write(the growth is at 6% );. The write function of the document object is used to send HTML data to the current document. Window object It represents the browser window created when the browser application is running. The window object is also the topmost container in the hierarchy of browser objects. It contains the document that is currently loaded and all the elements of the document. It also contains other objects such as menu bar, toolbar, status bar, frames e.t.c. Properties of the window object Closed indicates whether the window is closed or not. Defaultstatus displays a default message on the status bar Document the document that is currently loaded in browser window History accesses the history object of the window. This records the earlier accessed locations. Location it accesses the location object of the window, indicating the URL of the loaded document. Status it provides access to the windows status bar. This can be assigned a text message to be displayed. Methods of the window Blur () removes focus from the window Cleartimeout(timeout) it clears the specified time out. Close () closes the window.

Dialog boxes These are simple ways of interacting with the user. It could be used to alert the user on something using the alert dialog box, ask the user to confirm something using confirm dialog box or prompt the user for some input using prompt dialog box. Alert box. It is often used if you want to make sure that information goes through to the user. When an alert box pops up the user has to click ok to proceed. Syntax Alert(sometext); <html> <head> <script type="text/JavaScript"> functionshow_alert() { alert("welcome to my homepage"); } </script> </head> <body> <input type="button" onclick="show_alert()" value="Show alert box" /> </body> </html> Confirm box Used if you want the user to accept or verify something. When a confirm box pops up the user will have to click either ok or cancel to proceed. If the user clicks on ok the box returns true. If the user clicks cancel the box returns false. Syntax

Confirm(sometext);
<html> <head> <script type="text/JavaScript"> function show_confirm() { var r=confirm("Press a button"); if (r==true) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show confirm box" /> </body> </html>

Prompt box It 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 and if the user clicks cancel the box returns null. Syntax Prompt(sometext,default value); <html> <head> <script type="text/JavaScript"> functionshow_prompt() { var name=prompt("Please enter your name","Name"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); }

} </script> </head> <body> <input type="button" onclick="show_prompt()" value="Show prompt box" /> </body> </html> Document object Provides access to a web page that is displayed in a web browser window. An important thing about the document object is that from the document object it is possible and quite easy to access the elements that make the document including forms and their elements. Properties of the document object Alinkcolor.-Gives the color of the active link. bgcolor.-Gives the document background color. Fgcolor-Gives the document foreground color Lastmodified-Gives the date the file was last modified Title- Provides access to the documents title. Vlinkcolor-Specifies the color of visited links. Location-Specifies the URL of the document. Methods of the document object Close ()-Closes the output to the document object. Write(expression)-It writes the given HTML expression to the current document. Getselection ()-It captures the selected content from the document into a variable. These examples assign new values to the bgproperty of the document object. <html> <head> <script type= "text/JavaScript"> functionchgblue() { window.status="changed to blue"; document.bgcolor="blue" alert("background color is now blue"); }

functionchgpurple() { windows.status="change to purple"; document.bgcolor="purple" alert("background color is now purple); } functionchgred() { windows.status="changed to red"; document.bgcolor="red" alert("background color is now red"); } </script> </html> <form> <input type="button" name="btnblue" value="blue" onclick="chgblue"()"> <input type="button" name="btnpurple" onclick=chgpurple()"> <input type="button" name="btnred" onclick="chgred ()"> </form> Navigator object It contains information about the web browser as a whole such as the browser version number, the platform it is running on e.t.c. the navigator object have atleast 5 properties. - AppName.-It refers to the simple name of the browser. - AppVersion-Specifies the browsers version number. - Appcodename-Specifies the code name of the browser. - Platform-Specifies the hardware platform on which the web browser is running on. - Usergent-Refers to the string that the browser sends in itsusergent HTTP header. This typically containsthe Appname and Appversion. <html> <head> <body> <script type="text/JavaScript">

varbrowserName=Navigator.AppName; varbrowserver=parseInt(Navigator.App version); if (browser Name="mozilla&&browserver>=4)II (browserName="opera &&browserName>=3.1)) version=n3"; else version=n2"; if(version=="n3") alert("your browser passes the test"); else alert("you need to upgrade your browser); </script> </head> </body></html> Location object The location property of a window is a reference to the location object i.e. a representation of the URL of the document currently being displayed in that window. This property of the window is readable and writable. When it is read it contains the URL of the current window and when it is written to, a URL is assigned to the window.location and the browser notes the URL in the current window. Properties of the location object Window.location.-it contains the complete URL of the document currently being displayed. - Location.protocol-specifies the protocol of the current URL. - Location.host-specifies the hostname of the current URL. -Location.pathname-specifies the path to the final document in the URL. -Location.search- searches anything after the question mark. History object It contains an array of recently visited URLs. However because of security and privacy reasons the actual elements of the array are not accessible. Properties of the history object History.length-it gives the number of URLs the browser has visited. History.back- this programmatically makes the browser to go back to the previously visited URLs. History,forward-This programmatically makes the browser to go forward.

Methods

- History.go (n)- Makes the browser programmatically make n steps forward or backward where n is a positive or negative integer. If n is positive the browser moves forward. If n is negative the browser moves backward and if n is zero the current document is loaded. Link array It is used to access all link elements in a document. Image object It is used to access an image that is embedded in a HTML document. Area object It is used to access an area defined within a client site image map. Form object It is used to access a form within a HTML document.

JAVASCRIPT OBJECTS String object Every string, variables and literals in JavaScript belong to a built in object called string. The most important property that a string object has is its length which indicates the number of characters in the string.E.gwindows2000.length which results to a length of 11. Below are some of the methods of the string object:Stringobj.toUp perCase()- Converts a string to uppercase. Non-letters do not change.Windows2000.toUpperCase() will result to WINDOWS2000. Stringobj.toLowerCase()- converts the string object to lower case. Non-letters do not change. Stringobj.bold()- It returns a new string containing the original string enclosed in HTML tags to makethe string appear bold when displayed on a page. Windows2000.bold()results to <b>windows2000</b> Stringobj.italics()- It returns a new string containing the original string enclosed in HTML tags to make the string appear in italics when displayed on a page.E.g.windows2000.italics () results to <i>windows2000</i>. Stringobj.charAt()- It returns a string containing the single character at position index in the string where position zero refers to the first character in the string.E.g.windows2000.charAt (2) which results to n. Stringobj.indexOf()- It returns the position (starting from zero for the first character) where the target string can be inside the string. When a target cannot be found -1 is returned. If the optional start parameter is given, the search starts at the position ignoring any occurrence of the target before that position.E.g.windows2000.indexof (n) results to 2. Windows2000.indexof (s, 8) results to -1. Stringobj.LastIndexOf()- It works the same way as indexof() except that it searches backwards starting from the end of the string and reports the first match it encounters.E.g.windows2000.lastindexof (0) results to 10. Windows2000.lastindexof (s,8) results to 6.

Stringobj.substring(). It returns a substring of the string containing characters starting a position start and ending one position before the end. If the end is not specified the substring starts from the start and goes to the end of the string. E.g. windows2000.substring (4, 9) results to ows20. Windows2000.substring (9) results to 00. Math object. It provides a set of methods for mathematical manipulations and functions. It is an inbuilt object because it is not necessary to instantiate the mathobject. Some of the properties of the math object include:LN10- It is the natural logarithm of 10. PI- It is the constant pi property of a circle. SQRT 1_3 -This gives a square root of a third. SQRT4-This gives the square root of 4.

Some of the methods of the math object include:Cos(x)- It returns the cosine of x. Log(x)- It returns the natural logarithm of x. Max(x, y)- It returns the greater value between x and y. Min(x, y)- it returns the lesser value between x and y. Pow(x, y)- it returns x raised to power y. (x y). Random()- It returns a random number between 0 and 1.

Date object. It is used to work with dates and time. It is created with the date constructor date(). There are four ways of instantiating the date:- New Date () //current date and time. - New date(milliseconds) // milliseconds since 1970/01/01. - New date (date string) -New date (year, month, day, hours, minutes, seconds, milliseconds e.t.c.). e.g. today=new date() d1=new date (February 13 2012,13.12.00) d2=new date(2012,02,13) d3=new date(2012,02,13,13,13,12,00) Once the date object is created a number of methods allows you to operate on it. Most methods allow you get and setthe year, month, day, hour, minutes and milliseconds of the date object. E.g. we can use the date object to set a specific date. Var mydate=new date(); Mydate.setfullyear (2012,2,13); To set date to be 5 days in future

Varmydate=new Date(); Varmydate=new date(); Mydate.setDate(mydate.getdate()+5); Array object An array is a data structure consisting of several elements all of which have the same data type. In JavaScript arrays are objects just like the window and document object. An array is declared as a new instance of the pre-defined array object. E.g. varmycolors=new Array (6); Number six specifies the number of arrays or the number of items an array can hold. To include elements within the array one uses the reference to the array element as if it were a variable. E.e. mycolors[2]= green; Methods of array object. Join() - Joins all elements of the array into one long string. E.g. Var mycolor=new array(gree, orange, blue,red) Document.write(mycolors.join()); Pop()- It removes the last element from an array and returns the value of that Var mycolor=new array(green, orange, blue, red) Document.write(mycolors.pop()); This returns red. element. E.g

Push()-It adds all parameter values to the end of the array and returns a new (longer) length of the array. E.g. Var a =new array(1,2,3) Var length=a.push(4, 5); Reverse()- reverses the order of the elements within the array. E.g. Var a =new array(1,2,3) a.reverse() document.write(a.join()) which results to 3,2,1. Sort()- turns all elements of the array into strings and sorts them into lexicographic order(where the string 80 comes before 9 even though 9 is a lower number than 80) e.g. Var a=new array(m,80,a,9,z) a.sort() document.write(a.join()) writes 80,9,a, m,z to the current page

EVENT HANDLING
JavaScript programs are typically event driven. Events are actions that occur on the webpage usually as a result of something the user does. E.g. a button click is an event. It is these events that cause JavaScript programs to spring into action. E.g. if you move your mouse over a phrase a message can pop up. An event is the action that triggers an event handler. Event handlers are JavaScript codes that are not added inside the script tags but rather the HTML tag that executes JavaScript when something happens. Syntax Name-of-handler=JavaScript code; The table below illustrates some of the most used events:Event Click mouseOver MouseOut Load Unload Change Select Resize Focus Blur Submit e.g. <html> <head> <script type=text/javscript> Function inform() { Alert(breaking news! The nine pm news will be aired at ten); } Occurs when User moves mouse pointer over a link or anchor. User moves a mouse pointer off of a link or anchor User loads the page in the browser A user exits a page User changes the value of text area, text or select elements User selects form inputs element input fields User resizes the browser window User gives form element input focus User removes input focus from a form element User submits a form Event handler Onclick onMouseOver onMouseOut OnLoad onUnLoad onChange Onselect onResize onFocus onBlur onSubmit

</script></head> <body onload= inform()) <form name= go> <input type= checkbox name= color1 onclick= document.bgcolor= blue> <input type= checkbox name= color2 onclick= document.bgcolor= red> </form> </body> </html> Accessing and validating forms in JavaScript <html> <head><script type="text/JavaScript"> functioncheckForm() { var a=document.forms["myForm"]["email"].value; varatpos=a.indexOf("@"); vardotpos=a.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=a.length) { alert("enter a valid e-mail address"); return false; } } </script> </head> <body> <form name="myForm" action="demo_form.asp" method="post" onsubmit="return checkForm();" > Email: <input type="text" name="email"> <input type="submit" value="Submit">

</form>

ACTIVE X AND ACTIVE X CONTROLS ACTIVE X It is a framework for defining re-usable software components that perform a particular function or a set of functions in MS-windows in a way that it is independent of the programming language to implement them. A software application can be composed of one or more of these components in order to provide its functionality. It was introduced by Microsoft as a development of its component object (COM) and object linking and embedding (OLE) technologies and its commonly used in its windows operating system. Many MS-windows applications such internet explorer, MS-office, MS-visual studio and windows media player use active-x control to build their feature-set and also encapsulate their own functionality as active-x controls which can then be embedded into other applications. Internet explorer also allows embedding active-x controls onto web pages. ACTIVE-X CONTROLS. Active-x can serve to control distributed applications that work over the internet through web browsers. E.g. include customized applications for gathering data; displaying animations etc. one can compare active-x controls in some sense to java applets. However they also differ:Java applets can run nearly on any platform while active-x components officially operate only with Microsoft internet explorer web browser and MS-windows OS. - Programmers can grant active-x controls a much higher level of control over windows than java applets ever achieve making them more powerful but also potentially more dangerous.

Other active-x technologies in use also include:-active-x data objects (ADO) - Active server pages -active messaging - Active scripting

Das könnte Ihnen auch gefallen