Monday, December 9, 2019
Document Object Model, free essay sample
JavaScript is a scripting language, that is,à lightweight, dynamic,à loosely typed,à prototype-basedà programming language which is used in many different environments. * A lightweight programming language that isà interpretedà by the browser engine when the web page is loaded. * Dynamicà programming languages execute at runtime; they are not compiled. Because of this, JavaScript is sometimes considered a scripting language as opposed to a true programming language (obviously a misconception). When you have JavaScript within an HTML document it will be parsed as the page loads within the browser, hence at runtime. Loosely typedà languages do not insist upon any strong typing system. If youââ¬â¢ve programmed in C or Java (not the same as JavaScript) youââ¬â¢ll know that when declaring a variable you have to specify a type such as ââ¬Ëintââ¬â¢ (integer). JavaScript is different in that you donââ¬â¢t need to specify the type. * To perform inheritance within JavaScript you have to use something calledà prototypes. JavaScript does not support classes. Features of Java Script. * * JavaScript isà Browser Side Scripting Language. * Script that executes on local Browser is calledà browser side scripting. Usually Client / web surferââ¬â¢s PC is called local PC. * JS Script is embedded in the HTML page, * When user requests particular page containing script, script executes in local browser. * JavaScript is designed to add interactivity to HTML pages. Adding JavaScript to your HTML code allows you to change completely the document appearance, from changing text, to changing colors, or changing the options available in a drop-down list, or switching one image with another when you roll your mouse over it and much more. JavaScript can be used to make HTML pages more dynamic. All plain HTML files are static. JavaScript isà Lightweight Programming Language. * JS addsà programming facilityà to HTML page. * JS provides usà programming facilities to certain extends. such as ââ¬â Loops, A rrays, Decision making etc. * JavaScript isà embedded directly into HTML pages. * JavaScript is anà interpreted language. One of the main advantages of using JavaScript is that it is an interpreted language in which scripts are directly executed without preliminary compilation. You cant compile Javascript to bytecode and run it anywhere * Java Script isà Free to use. You are not required to purchase a license in order to use JavaScript. JavaScript is supported by many popular Web browsers, including all remotely recent versions of Microsoft Internet Explorer and Netscape Navigator, but sometimes you have to turn on the capabilities in your MOST COMMON USES * Browser Detection Detecting the browser used by a visitor at your page. Depending on the browser, another page specifically designed for that browser can then be loaded. * Cookies Storing information on the visitors computer, then retrieving this information automatically next time the user visits your page. This technique is called cookies. Control Browsers Opening pages in customized windows, where you specify if the browsers buttons, menu line, status line or whatever should be present. * Validate Forms Validating inputs to fields before submitting a form. An example would be validating the entered email address to see if it has an @ in it, since if not, its not a valid address. How does it work? JavaScript is what is called a Client-side Scripting Language. That means that it is a computer programming language that runs inside an Internet browser. Inside a normal Web page you place some JavaScript code. When the browser loads the page, the browser has a built-in interpreter (also called JavaScript engine) that reads the JavaScript code it finds in the page and runs it. JavaScript engine is different for each browser, and in fact may be different between versions of the same browser, WHERE TO PLACE IT Since javascript isnt HTML, you will need to let the browser know in advance when you enter javascript to an HTML page. This is done using theà lt;scriptgt;à tag. The browser will use theà lt;scriptgt; type=text/javascriptgt;à andà lt;/scriptgt;à to tell where javascript starts and ends. Consider this example: lt;htmlgt; lt;headgt; lt;titlegt;My Javascript Pagelt;/titlegt; lt;/headgt; lt;bodygt; lt;script type=text/javascriptgt; alert(Welcome to my world!!! ); lt;/scriptgt; lt;/bodygt; lt;/htmlgt;à | | The wordà alertà is a standard javascript command that will cause an alert box to pop up on the screen. The visitor will need to click the OK button in the alert box to proceed. THE FIRST SCRIPT Knowing that javascript needs to be entered betweenà lt;scriptgt;à tags, is a start. But there are a few other things you need to know before writing your first javascript: * Javascript lines end with a semicolon. You may have noticed from the example on the previous page that javascript lines end with a semicolon. You can easily put all your javascript on a single line without destroying the performance of it. However, you would destroy the overview of your script so it is not advisable. * Always put the text within . When entering text to be handled by javascript, you should always put the text within . If you forget to enclose your text in , javascript will interpret your text as being variables rather than text. In the next section you will learn why this would cause an error to your script. Capital letters are different from lowercase letters. You should always remember that capital letters are different from lowercase letters. This means that when you write commands in javascript, you need to type capital letters in the correct places, and nowhere else. Incorrect capitalization is probably the most common source of error for javascript programmers on all levels!! Consider following ex ample lt;htmlgt; lt;headgt; lt;titlegt;My Javascript Pagelt;/titlegt; lt;/headgt; lt;bodygt; lt;scriptgt; document. write(Welcome to my world!!! ); lt;/scriptgt; lt;/bodygt; lt;/htmlgt;à | | Theà document. writeà is a javascript command telling the browser that what follows within the parentheses is to be written into the document. When entering text in javascript you need to include it in . The script in the example would produce this output on your page: Welcome to my world!!! | | CAPITAL LETTERS It is extremely important to be aware that javascript makes a sharp distinction between capital and lowercase letters. Javascript does not consider a variable namedà myvalueà to be the same as a variable namedà MYVALUE. POP UP BOXES It is possible to make three different kinds of popup windows. ALERT BOX The syntax for an alert box is:à alert(yourtext); The user will need to click OK to proceed. Typical use is when you want to make sure information comes through to the user. Examples could be warnings of any kind. (Typical examples are Adult Content, or technical matters like This site requires Shockwave Flash plug-in). CONFIRM BOX: The syntax for a confirm box is:à confirm(Did you understand ? ); The user needs to click either OK or Cancel to proceed. Typical use is when you want the user to verify or accept something. Examples could be age verification like Confirm that you are at least 57 years old or technical matters like Do you have a plug-in for Shockwave Flash? à If the user clicks OK, the box returns the valueà true. If the user clicks Cancel, the box returns the valueà false. if (confirm(Do you agree)) {alert(You agree)} else{alert (You do not agree)};| | Note: Theà if statementà is explained later in this tutorial. PROMPT BOX: The prompt box syntax is:à prompt(yourtext,defaultvalue); The user must click either OK or Cancel to proceed after entering the text. Typical use is when the user should input a value before entering the page. Examples could be entering users name to be stored in a cookie or entering a password or code of some kind. à If the user clicks OK the prompt box returns the entry. If the user clicks Cancel the prompt box returnsà null. Since you usually want to use the input from the prompt box for some purpose it is normal to store the input in a variable, as shown in this example: username=prompt(Please enter your name,Enter your name here);à alert (Hello Mr. + username);| | IF AND ELSE The general syntax for if statements is: f (condition) {action1;} else {action2;} An example could be: if (browser==MSIE) {alert(You are using MSIE);} else {alert(You are using Netscape);}à | | Again it is important to note thatà ifà is written as if. Using the capital IF would cause an error. EVENTS Events are actions that can be detected by javascript. An example would be theà onmouseoverà event, which is detected when the user moves the mouse over an object. Another event is theà onloadà event, which is detected as soon as the page is finished loading. The following are the most important events recognized by javascript: Event| Detected when| HTML tagsà | nfocus=| Form field gets focus| select, text, textareaà | onblur=| Form field looses focus| select, text, textareaà | onchange=| Content of a field changes| select, text, textareaà | onselect=| Text is selected| text, textareaà | onmouseover=| Mouse moves over a link| Aà | onmouseout=| Mouse moves out of a link| Aà | onclick=| Mouse clicks an object| A, button, checkbox,à radio, reset, submità | onload=| Page is finished loading| body, framesetà | onunload=| Browser opens new document| body, framesetà | onSubmit=| Submit button is clicked| formà | | Events are used for two main purposes: 1. To perform a function upon detection of the event 2. To show a popup box upon detection of the event. Loops (for, while) for (variable=startvalue;à variablelt;=endvalue;variable=variable+incrementfactor)à { // Here goes the script lines you want to loop. } Arrays The following points should always be remembered when using arrays in JavaScript: * The array is a special type of variable. * Values are stored into an array by using the array name and by stating the location in the array you wish to store the value in brackets. Example: myArray[2] = Hello World; * Values in an array are accessed by the array name and location of the value. Example: myArray[2]; lt;script type=text/javascriptgt; lt;! var myArray = new Array(); myArray[0] = Football; myArray[1] = Baseball; myArray[2] = Cricket; document. write(myArray[0] + myArray[1] + myArray[2]); //gt; lt;/scriptgt; - javascript redirect Control over what page is loaded into the browser rests in the JavaScript propertyà window. location. By settingà window. locationà equal to a new URL, you will in turn change the current webpage to the one that is specified. If you wanted to redirect all your visitors to www. oogle. com when they arrived at your site, you would just need the script below: lt;script type=text/javascriptgt; lt;! window. location = http://www. google. com/ //gt; lt;/scriptgt; Object Oriented Programming in java Script 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, th en create new object instances. Creating a Direct Instance lt;scriptgt; var person=new Object(); person. firstname=John; erson. lastname=Doe; person. age=50; person. eyecolor=blue; document. write(person. firstname + is + person. age + years old. ); lt;/scriptgt; Using an Object Constructor lt;scriptgt; function person(firstname,lastname,age,eyecolor) { this. firstname=firstname; this. lastname=lastname; this. age=age; this. eyecolor=eyecolor; } myFather=new person(John,Doe,50,blue); document. write(myFather. firstname + is + myFather. age + years old. ); lt;/scriptgt; Inheritance in JavaScript To perform inheritance within JavaScript you have to use something calledà prototypes. JavaScript does not support classes. Functions The general syntax for a function is: function functionname(variable1,à variable2, ,à variableX) { // Here goes the javascript lines for the function } Aà typical bug when entering javascript functions is to forget about the importance of capitals in javascript. The wordà functionà must be spelled exactly asà function. Functionà orà FUNCTIONà would cause an error. Document Object Model The Document Object Model, normally abbreviated to DOM, is the API through which JavaScript interacts with content within a website. JavaScript and the DOM are usually seen as a single entity since JavaScript is most commonly used for this purpose (interacting with content on the web). The DOM API is used to access, traverse and manipulate HTML and XML documents. * Window object:à Top of the hierarchy. It is the outmost element of the object hierarchy. * Document object:à Each HTML document that gets loaded into a window becomes a document object. The document contains the content of the page. * Form object:à Everything enclosed in the lt;formgt; lt;/formgt; tags sets the form object. Accessing DOM nodes The following text is a snippet of HTML taken from a regular HTML document. - lt;p title=The test paragraphgt;This is a sample of some lt;bgt;HTML you mightlt;brgt;havelt;/bgt; in your documentlt;/pgt; The DOM tree views this (simplified) as follows: - P - _______________|______________ - | | - hildNodes attributes - ______________|___________ | - | | | title = The test paragraph - This is a sample of some B in your document - | - childNodes - __________|_______ - | | | HTML you might BR - | - have Letââ¬â¢s assume we have a basic XHTML document containing a paragraph and an unordered list: lt;! DOCTYPEà htmlà PUBLICà -//W3C//DTDà XHTMLà 1. 0à Strict//ENà http://www. w3. org/TR/xhtml1/DTD/xhtml1-strict. dtdgt;à à lt;htmlà xmlns=http://www. w3. org/1999/xhtmlà lang=engt;à à à à à à lt;headgt; lt;metaà http-equiv=Content-Typeà content=text/html;à charset=UTF-8à /gt;à à à à à à à à à à à à à à lt;titlegt;Java Script! lt;/titlegt;à à à à à à lt;/headgt; lt;bodygt; lt;pà id=introgt;Myà firstà paragraph lt;/pgt; lt;ulgt; lt;ligt;Listà itemà 1lt;/ligt;à à à à à à à à à à à à à à lt;ligt;Listà item 2lt;/ligt;à à à à à à à à à à à à à à lt;ligt;Listà itemà 3lt;/ligt; lt;ligt;Listà itemà 4lt;/ligt;à à à à à à à à à à à à à à lt;ligt;Listà itemà 5lt;/ligt;à à à à à à à à à à lt;/ulgt; lt;scriptà type=text/javascriptgt;à à à à à à à à à à //à lt;! [CDATA[ //à ]]gt; lt;/scriptgt; lt;/bodygt; lt;/htmlgt; In this first example weââ¬â¢re going to access our paragraph by using the ââ¬ËgetElementByIdââ¬â¢ DOM method: 1. varà introParagraphà =à document. etElementById(intro);à à 2. //à Weà nowà haveà aà referenceà toà theà DOMà node. Thisà DOMà à 3. //à nodeà representsà theà introà paragraph. The variable ââ¬ËintroParagraphââ¬â¢ is now a reference to the DOM node. We can do a number of things with this node, ââ¬â we can query its content and attributes, and can manipulate any aspect of it. We can remove it, clone it or move it to other parts of the DOM tree. Anything which is present within a document we can access using JavaScript and the DOM API. So, we might want to access the unordered list in a similar fashion, the only problem is that it doesnââ¬â¢t have an ID. You could give it an ID and then use the same method as above or we could access it using ââ¬ËgetElementsByTagNameââ¬â¢: varà allUnorderedListsà =à document. getElementsByTagName(ul); getElementsByTagName The ââ¬ËgetElementsByTagNameââ¬â¢ method returns a live node collection/list. Itââ¬â¢s similar to an array in that it has a length property. One important thing to note is these collections are live ââ¬â if you add a new element to the DOM then the collection will update itself. Since itââ¬â¢s an array-like object we can access each node via an index, from 0 to the total length of the collection (minus 1): /à Accessà singleà unorderedà list:à [0]à index varà unorderedListà =à document. getElementsByTagName(ul)[0]; //à Createà Nodeà listà ofà allà listà itemsà withinà theà UL:à à varà allListItemsà =à unorderedList. getElementsByTagName(li); //à Now,à weà canà loopà throughà eachà listà itemà usingà aà FORà loop:à à forà (varà ià =à 0,à lengthà =à allListItems. length;à ià lt;à length;à i++)à {à à à à à à //à Extractà textà nodeà withinà andà alertà itsà content:à à à à à à alert(à allListItems[i]. firstChild. dataà ); } Traversing the DOM The term traverse is used to describe the action of travelling through the DOM, finding nodes. The DOM API gives us plenty of node properties which we can use to move up and down through all the nodes within a document. These properties are inherent of all nodes and enable you to access related/close nodes: * Node. childNodes: You can use this to access all direct child nodes of a single element. It will be an array-like object, which you can loop through. Nodes within this array will include all the different node types including text nodes and other element nodes. * Node. firstChild: This is the same as accessing the first item in the ââ¬ËchildNodesââ¬â¢ array (ââ¬ËElement. childNodes[0]ââ¬Ë). Itââ¬â¢s just a shortcut. * Node. astChild: This is the same as accessing the last item in the ââ¬ËchildNodesââ¬â¢ array (ââ¬ËElement. childNodes[Element. childNodes. length-1]ââ¬Ë). Itââ¬â¢s just a shortcut. * Node. parentNode: This gives you access to the parent node of your current node. There will only ever be one parent node. In order to access the gr andparent you would simply use ââ¬ËNode. parentNode. parentNodeââ¬â¢ etc. * Node. nextSibling: This gives you access to the next node on the same level within the DOM tree. * Node. previousSibling: This gives you access to the last node on the same level within the DOM tree. lt;! DOCTYPE html PUBLIC -//W3C//DTD XHTML 1. Strict//EN http://www. w3. org/TR/xhtml1/DTD/xhtml1-strict. dtdgt; lt;html xmlns=http://www. w3. org/1999/xhtml lang=engt; lt;bodygt; lt;divgt; lt;pgt;Hello worldlt;/pgt; lt;ulgt; lt;ligt;Aapplelt;/ligt; lt;ligt;Pearlt;/ligt; lt;ligt;Melonlt;/ligt; lt;/ulgt; lt;/divgt; lt;script type=text/javascriptgt; var theDiv = document. getElementsByTagName(div)[0]; var p = theDiv. firstChild; var ul = p. nextSibling; alert(ul. childNodes[0]. data ); alert(ul. childNodes[1]); alert(ul. childNodes[2] ); lt;/scriptgt; lt;/bodygt; lt;/htmlgt;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.