javascript

Posted on at



JavaScriptIntroductionTable of Contents1.

Introduction to JavaScript• What is JavaScript• Uses of JavaScript• Writing JavaScirpt2. Programming Basics• Variables• Functions3. JavaScript Objects• Objects• Properties• Methods4. Document and Window Objects• Write to a Document• Open a Window5. JavaScript Events• Events and Objects• Image RolloversRevised 

IntroductionJavaScript OriginsJavaScript 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 elementsWith JavaScript you can show, hide, change, resize images, andcreate image rollovers. You can create scrolling text across the statusbar.• Create pages dynamicallyBased on the user's choices, the date, or other external data, JavaScriptcan produce pages that are customized to the user.• Interact with the userIt can do some processing of forms and can validate user input whenthe user submits the form.4Writing JavaScriptJavaScript code is typically embedded in the HTML, to be interpreted andrun by the client's browser. Here are some tips to remember when writingJavaScript 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 TagThe <SCRIPT> tag alerts a browser that JavaScript code follows. It istypically 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.")</SCRIPT>5• Save the changes by choosing Save from the File menu.• Then Refresh the browser by clicking the Refresh or Reload button.Implementing JavaScriptThere are three ways to add JavaScript commands to your Web Pages.• Embedding code• Inline code• External fileExternal FileYou can use the SRC attribute of the <SCRIPT> tag to call JavaScript codefrom an external text file. This is useful if you have a lot of code or youwant to run it from several pages, because any number of pages can call thesame external JavaScript file. The text file itself contains no HTML tags. Itis call by the following tag:<SCRIPT SRC="filename.js"></SCRIPT>External Example• Open "external.html" in a browser• View the Source• Put the cursor after <! – Enter code here Æ and enter:<SCRIPT language = "JavaScript" SRC = "external.js"></SCRIPT>• Save the changes and Refresh the browser.62 Programming BasicsProgrammers use variables to store values. A variable can hold several typesof data. In JavaScript you don't have to declare a variable's data type beforeusing it. Any variable can hold any JavaScript data type, including:• String data• Numbers• Boolean values (T/F)Variable NamesThere are rules and conventions in naming variables in any programminglanguage. It is good practice to use descriptive names for variables. Thefollowing are the JavaScript rules:• The variable name must start with a letter or an underscore.firstName or _myName• You can use numbers in a variable name, but not as the firstcharacter.name01 or tuition$• You can't use space to separate characters.userName not user Name• Capitalize the first letter of every word except the firstsalesTax or userFirstNameVariables• To declare variables, use the keyword var and the variable name:var userName7• To assign values to variables, add an equal sign and the value:var userName = "Smith"var price = 100FunctionsWith functions, you can give a name to a whole block of code, allowing youto reference it from anywhere in your program. JavaScript has built-infunctions for several predefined operations. Here are three some functions.• alert("message")• confirm("message")• prompt("message")Function Example• Open "functions. html" and View the Source• Put the cursor after " // add code here " and enter:• var userNamevar willDoSurveyuserName = prompt("Enter your name", "")alert("Thank you, " + userName)• Save the changes and Refresh the pageUser-Defined FunctionsWith user-defined functions, you can name a block of code and call it whenyou need it. You define a function in the HEAD section of a web page. It isdefined with the function keyword, followed by the function name and anyarguments.function functionName(argument){statements}User-Defined Example8RUN THE FUNCTION• Open "userdefined.html" and View the Source• Put the cursor after "<! – enter function Æ" and enter:<SCRIPT language = "JavaScript">function showAlert() {alert("this is a user-defined function.")}</SCRIPT>• In the BODY, put the cursor after "<! – enter the button def here ->"and enter:<INPUT type-"button" value="Run the Function"onClick="showAlert()">• Save the changes and Refresh the browser.93 ObjectsJavaScript supports programming with objects. Objects are a way oforganizing the variables. The different screen elements such as Web pages,forms, text boxes, images, and buttons are treated as objects.Properties and MethodsEvery object has its own properties and methods.• Properties define the characteristics of an object.Examples: color, length, name, height, width• Methods are the actions that the object can perform or that can beperformed on the object.Examples: alert, confirm, write, open, closeNaming Objects• Objects are organized in a hierarchy. To refer to an object use :objectName• To refer to a property of an object use:objectName.propertyName• To refer to a method of an object use:objectName.methodName()Built-In ObjectsSome of the built-in language objects of JavaScript offer more advancedoperations such as:• Math – provides for math calculations• Date – provides date and time information• String – provides for string manipulation10Math ObjectThe Math object provides methods for many mathematical calculations,including: abs(), log(), pow(), random(), round(), sqrt()Format: Math.method(#)Math Example• Keep the "userdefined.html" file open• Put the cursor in the BODY section and enter:• <SCRIPT language = "JavaScript">var theNumber = 3.14myNum = Math.round(theNumber)</SCRIPT>• Save the changes and Refresh the pageDate ObjectThe Date object provides the day, date, and time information.Format: dateObject.method()Date Example• Keep the "userdefined.html" file open• Put the cursor in the BODY section and enter:• <SCRIPT language = "JavaScript">var rightNow = new Date()theYear = rightNow.getFullYear()</SCRIPT>• Save the changes and Refresh the pageString Object11The String object provides methods and properties for string manipulationand formatting.Format: stringName.method()String Example• Keep the "userdefined.html" file open• Put the cursor after the Date example and enter:var theString = "my name"var printString = theString.bold()var numChars = theString.length</SCRIPT>• Save the changes and Refresh the pagetheString = Jane SmithprintString = Jane SmithnumChars = 10124 Document ObjectThe Document object represents the Web page that is loaded in the browserwindow, and the content displayed on that page, including text and formelements.Document MethodsYou can use the methods of the document object to work on a Web page.Here are the most common document methods:• write() - write a string to the Web page• open() - opens a new document• close() - closes the documentDocument Example• Keep the "userdefined.html" file open• Put the cursor after the String example and enter:document.write(myNum)document.write(theYear)document.write(printString)document.write(numChars)</SCRIPT>• Save the changes and Refresh the pageFormatting What is WrittenYou will notice that the results of all four variable are printed on one lineand without any spaces between the results. You can avoid this by includingsome formatting in your "document.write" statement.13Document Formatting Example• Open "write.html" and View the Source• Put the cursor after "<! – enter function Æ" and enter:<SCRIPT language="JavaScript">function newPage() {var userName = prompt("Please enter your name:", "")document.write("<H1>Welcome " + userName + "</H1><BR>")document.write("<H2>to your new home page.</H2>")}</SCRIPT>• Put the cursor after "<! – enter the link here Æ" and enter:<A HREF="JavaScript:newPage()">Create-a-Page!</A>• Save the changes and Refresh the pageDocument PropertiesUse the properties of the document object to set the colors of the page, thetitle and display the date the document was last modified. JavaScript hasabout 150 defined color words you can use or you can provide thehexidecimal RGB codes. Here are the most common document properties:• bgColor• fgColor• linkColor• vlinkColor• title• lastModifiedDocument Example• Keep the "write.html" file open• Put the cursor after the last "document.write" and enter:document.bgColor="red"• Save the changes and Refresh the page14Window ObjectThe window object represents the browser window. You can use it to open aWeb page in a new window and to set the attributes for the window. Thereare only two main window properties. They are:• status - set the status bar message• self - stores the name mof the current windowWindow MethodsThe window methods are mainly for opening and closing new windows.The following are the main window methods. They are:• alert() - to display a message box• confirm() - to display a confirmation box• prompt() - to display a prompt box• open() - to open a new window• close() - to close a windowWindow Example• Open the "window.html" file and View the Source• Put the cursor after "<! – Enter the function here Æ" and enter:<SCRIPT language = "JavaScript">function openWin() {window.open("windowtoo.html")}</SCRIPT>• Put the cursor after "<!—Add link here Æ" and enter:<A HREF="JavaScript:openWin()">New Window!</A>• Save the changes and Refresh the page15Window AttributesIf the default new window does not suit your needs, you can specifydifferent features of the window when you open it. The complete syntax ofthe "window.open" is as follow:window.open(URL, windowName, featureList)By default, if you do not specify any features, then a window will have all ofthem. If you specify any one feature, then the window will have only thoseyou set equal to 1. The following are the window attributes:• toolbar• menubar• scrollbars• resizeable• status• location• directoriesWindow Attributes Example• With the "window.html" file open, View the Source• Put the cursor on the line "window.open " and edit it to:window.open("windowtoo.html", "newWindow","height=200,width=200,")• Save the changes and Refresh the page165 Objects and EventsThe JavaScript Object HierarchyWindowHistory Document Location FrameLink Anchor Form ImageText TextareaPassword ButtonSubmit ResetRadio CheckboxSelect Hidden17EventsThe objects in a Web pages are organized in a hierarchy. All objects haveproperties and methods. In addition, some objects also have "events".Events are things that happen, usually user actions, that are associated withan object. The "event handler" is a command that is used to specify actionsin response to an event. Below are some of the most common events:• onLoad - occurs when a page loads in a browser• onUnload - occurs just before the user exits a page• onMouseOver - occurs when you point to an object• onMouseOut - occurs when you point away from an object• onSubmit - occurs when you submit a form• onClick - occurs when an object is clickedEvents and ObjectsEvents are things that happen, actions, that are associated with an object.Below are some common events and the object they are associaated with:Event ObjectonLoad BodyonUnload BodyonMouseOver Link, ButtononMouseOut Link, ButtononSubmit FormonClick Button, Checkbox, Submit,Reset, LinkExample: <FORM onSubmit="functionName()">Image Rollover18Replacing one image with a second image when the user moves the mouseover it is called a "rollover". The events called for are the "onMouseOver"and "onMouseOut". The object used with these events can be a link or abutton.Image Rollover Example• With the "window.html" file open, View the Source• Put the cursor after the line "<A HREF=" and enter:<P><A HREF="URL"onMouseOver="document.hot.src='hot1.gif'"onMouseOut="document.hot.src='hot2.gif'"><IMG name="hot" src="hot2.gir"> </A>• Save the changes and Refresh the page.



About the author

160