Document Object Model,

9 September 2016

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, Arrays, Decision making etc. * JavaScript is embedded directly into HTML pages.

Document Object Model, Essay Example

* 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 can’t 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 visitor’s 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 browser’s 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, it’s 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 isn’t HTML, you will need to let the browser know in advance when you enter javascript to an HTML page. This is done using the <script> tag. The browser will use the <script> type=”text/javascript”> and </script> to tell where javascript starts and ends. Consider this example: lt;html> <head> <title>My Javascript Page</title> </head> <body> <script type=”text/javascript”> alert(“Welcome to my world!!! “); </script> </body> </html> | | 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 <script> 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 example <html> <head> <title>My Javascript Page</title> </head> <body> <script> document. write(“Welcome to my world!!! “); </script> lt;/body> </html> | | 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 user’s 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; variable<=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]; <script type=”text/javascript”> <! — var myArray = new Array(); myArray[0] = “Football”; myArray[1] = “Baseball”; myArray[2] = “Cricket”; document. write(myArray[0] + myArray[1] + myArray[2]); //–> </script> ————————————————- 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: <script type=”text/javascript”> <! — window. location = “http://www. google. com/” //–> </script> 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, then create new object instances. Creating a Direct Instance <script> 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. “); </script> Using an Object Constructor <script> 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. “); </script> 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 <form>… </form> tags sets the form object. Accessing DOM nodes

The following text is a snippet of HTML taken from a regular HTML document. ————————————————- <p title=”The test paragraph”>This is a sample of some <b>HTML you might<br>have</b> in your document</p> 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: <! DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1. 0 Strict//EN” “http://www. w3. org/TR/xhtml1/DTD/xhtml1-strict. dtd”>   <html xmlns=”http://www. w3. org/1999/xhtml” lang=”en”>       <head> <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />               <title>JavaScript! lt;/title>       </head> <body> <p id=”intro”>My first paragraph… </p> <ul> <li>List item 1</li>               <li>List item 2</li>               <li>List item 3</li> <li>List item 4</li>               <li>List item 5</li>           </ul> <script type=”text/javascript”>           // <! [CDATA[ // ]]> </script> </body> </html> 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 < 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 grandparent 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. <! DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1. Strict//EN” “http://www. w3. org/TR/xhtml1/DTD/xhtml1-strict. dtd”> <html xmlns=”http://www. w3. org/1999/xhtml” lang=”en”> <body> <div> <p>Hello world</p> <ul> <li>Aapple</li> <li>Pear</li> <li>Melon</li> </ul> </div> <script type=”text/javascript”> 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] ); </script> </body> </html>

A limited
time offer!
Save Time On Research and Writing. Hire a Professional to Get Your 100% Plagiarism Free Paper