Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Javascript DOM: API introduction

This article shows the history, characteristics, details, and scripts that manipulate HTML elements via JavaScript using the DOM as the base technology.

The JavaScript language was originally developed by Brendan Eich (when he was working for Netscape) with the initial name "Mocha". Later, the name was modified to LiveScript and then for JavaScript. The "LiveScript" name was also used to launch the language along with the beta version of Netscape 2.0 browser in September 1995. The JavaScript name was adopted by Sun Microsystems in December of that year when it was implemented for the Netscape browser version 2.0B3.

The name change from LiveScript to JavaScript happened at the same time when Netscape added support for Java technology in its browsers (Applets). The choice was criticized for seeming a marketing strategy to take advantage of the popularity obtained by the recent Java release.

It didn’t take long for the JavaScript language to be widely accepted as a scripting language for client-side web pages. Due to this fact, Microsoft released a compatible dialect language named JScript to avoid trademark issues. JScript innovated by optimizing methods that improved data operations that had problems. Nowadays JavaScript and JScript are so similar that the two terms are commonly used interchangeably.

In November, 1996 Netscape announced that they had submitted JavaScript to the ECMA International organization as a candidate for an industry standard. The result was later announced as the Javascript’s standardized version called ECMAScript.

Since then, JavaScript has become one of the most popular web programming languages. Initially, many professionals give the language a bad reputation because it was targeted at non-technical professionals. When the Ajax emerged JavaScript got its popularity back and received more professional attention. Thus, the proliferation of frameworks, libraries, and improved programming practices, and its uses outside the browser became notorious cases for the language.

The CommonJS project was founded in January 2009 and its goal was to specify a standard library for JavaScript development outside the browser.

JavaScript x Java

It is unlikely that any programmer studying web programming has not been faced with this question: the Java and JavaScript goals are the same?

At first, many people think yes, because their names and both are web languages. See some distinctions demonstrations that these two languages have nothing in common.

JavaScript

  • Scripting Language without compilation;
  • HTML integrated code;
  • Interactions and pages effects;
  • Lack of code confidentiality;
  • Simple language.

Java

  • Programming language compiled with a JVM (Java Virtual Machine);
  • Platform independent;
  • Strongly typed;
  • Complex language;
  • Safety code resources.

Inserting JavaScript into a web page

The first thing to do is let the web browser know that some kind of script will be used instead of HTML by using the <script> tag. This tag is placed between the <head> and <body> tags of an HTML document and it can receive multiple scripts within the same page or just point to external .JS files. The call to external JavaScript files is a good practice as it acts as a repository containing all scripts stored in one place. This allows the developer to re-use the code on other pages by calling the .JS file and avoiding code repetition.

The examples shown in this article were created on HTML files using the Notepad++ editor.

Listing 1 shows a JavaScript code inside a HTML page that display a simple welcome message to the user.

Listing 1. Welcome code

<!DOCTYPE html> 
  <html>
   <head> 
   <title>Welcome Script</title>
    <script type="text/JavaScript"> alert("Welcome! "); </script> 
   </head> 
   <body> HTML Body </body>
   </html>

User interactivity through events

Events are mechanisms that link user actions to a given HTML document that deals with interactivity. They can also be thought as JavaScript events that let you know when an action happened. The aim of the events is to answer the interaction with web page using JavaScript code. Let's look at a list of the main events that this language supports:

  • onBlur: is activated when the user removes the focus of a page element. The focus is where the cursor is.
  • onChange: Changes the state of a form element. Sometimes doesn’t happen until the user remove the focus from an element.
  • onClick: Happens when the mouse button is clicked over a page element, usually a button or a link.
  • onFocus: Happens when a page element or the window gets the focus. Opposite of the "onblur" event.
  • onKeydown: Raised at the time a user presses a key regardless of whether or not releasing it.
  • onKeypress: Results of a clicked button for a specific time. Before that, it produces an "onekeydown" event when a key is pressed.
  • onKeyup: Raised when the user released the key.
  • onLoad: Happens when the page and the images have finished loading.
  • onMousedown: Happens when the user clicks on a page element regardless of releasing the click or not.
  • OnMouseMove: Happen when the mouse cursor moves across the page.
  • onMouseout: Happens when the mouse cursor withdrawal from the area occupied by a page element.
  • onMouseover: Happens when the mouse cursor enters the area occupied by a page element.
  • onMouseup: Happens when the user releases the mouse button clicked previously.
  • onMove: Occurs when the browser window or frame is moved.
  • onResize: Happens when the browser window or frame is resized.
  • onReset: Occurs when a user clicks the reset button on a form.
  • onSelect: Executes when a user selection an item from a form element.
  • onSubmit: Happens when the Submit button sends the form’s data. This event is executed before sending the data to the server.

The code in Listing 2 show how to work with some events mentioned above.

Listing 2. Working with events

<!DOCTYPE html>    
<html>    
<head>               
<title>Interactive Calculator</title>
  
<script language="JavaScript">
 
function mathExpression (form) {
 
form. results.value = eval(form.entry.value);
 
}
function mathExpression (form) 
{                           
form.entry.blur();                           
form.entry.value = prompt("Type a math expression. Example: 2 + 2","");                           
 
mathExpression(form);               
 
}                              
 
function clearFields(){                           
var entryValue = document.getElementById("entry").value;                           
var resultValue = document.getElementById("results").value;                                                      
 
// Clear the Values
entryValue = "";                           
resultValue = "";                                          
}    
</script>    
</head>     
<body> 
<h1>Calculate the math expression</h1>
<form method="post" onsubmit="clearFields()">  
Calculator:<input type="text" name="entry" value="" onFocus="mathExpression(this.form)">                           
<br>Result:<input type="text" name="results" value="" onFocus="this.blur()">              
<input type="submit" value="ClearFields">               
</form>     
</body>     
</html>
  

Listing 3 shows an example where the events check the mouse coordinates.

Listing 3. Verifying mouse coordinates

<html>   
<head>   
<title>Mouse coordinates via JavaScript</title>       
 
<script>               
function coordinates(event) {                                     
var x;                                      
var y;                                      
 
if (window.event){
// Get the coordinates for Internet Explorer or Google Chrome
x = window.event.clientX;                                                             
y = window.event.clientY;                                      
 
}
Else
{
// Get the coordinates for Google Chrome
x = event.clientX;                                                              
y = event.clientY;                                      
 
}                                          
 
document.getElementById("coordinates").innerHTML = "Current mouse coordinates: " + x + ", " + y;               
}               
 
document.onmousemove = coordinates;   
 
</script>   
</head>   
<body>                   
<div id="coordinates"></div>       
</body>   
</html>


Next we will show a script that uses images, functions and text display to interact with the uses. The following steps have to be designed in this scenario:

  1. Know when the page finishes loading.
  2. Know how to display the action so that the user can view it.

The first item requires a response of an event, probably one that runs when the page is loading. The second item requires using a predefined JavaScript feature. Listing 4 shows the complete example that asks the user name when the image is clicked. Make sure to have the files sad.jpg and happy.jpg on the same folder of the HTML file that contains the code on Listing 4.

Listing 4. Interacting with the user

<!DOCTYPE html>    
<html>               
<head>                           
<title>User interaction</title>                           
<script type="text/JavaScript">                                      
function helloSmile(){                                                 
 
var userName = prompt("What’s your name?", "Type here");                                                  
 
if(userName)
{                                                              
alert('Nive to meet you, '+userName);                                                              
 
document.getElementById("idImgHappy ").src = "happy.jpg";
 
}                                      
} 
</script>               
</head>               
<body onload="alert('Hello User. Click on the image to interact with this page!');">                           
 
<div style="margin-top:100px; text-align:center">                                      
 
<img id="idImgHappy" SRC="sad.jpg" alt="sad" onClick="helloSmile()" style="cursor:pointer"/>                  
 
</div>                            
</body>    
</html>


Creating Smart Functions

Functions are small reusable pieces of code that are efficient and allow the division of a big problem into small solutions. The reasons to use functions are: task division, code organization and troubleshooting. Create a system based on functions is a smart since they make the script simpler and organized. Usually a function is employed when events are needed of when a page is submitted to another page.

Listing 5 contain an example of and HTML component manipulation known as "dual list" that show how to select one or more elements.

Listing 5. Selection of two or more elements

<!DOCTYPE html>   
<html>    
<head>    
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />    
<title>Transfer items - Dual List</title>    
</head>        
<script>               
var strDes;               
var strRem;                   
 
function onMoveItem(objRemetente, tdRemetente, objDestino, tdDestino)
{                              
var totalRem;               
var totalDes;               
var strtemp; 
var strValor;                              
 
strDes = "<SELECT id='" + objDestino.id + "' style='WIDTH: 130px; height: 100px'  name='" + objDestino.id + "' multiple='multiple' onchange='setaValor(this.id);'  height='200px'>";
 
strRem = "<SELECT id='" + objRemetente.id + "'  style='WIDTH: 130px; height: 100px'  name='" + objRemetente.id + "' multiple='multiple' onchange='setaValor(this.id);'  height='200px'>";                           
totalRem = objRemetente.length;               
totalDes = objDestino.length;                               
 
for (i=0; i < totalDes; i++){                           
 
        strValor = objDestino.options[i].text;                           
  strDes += "<option value='" + strValor + "'>" + strValor + "</option>";               
 
}                                  
 
for (i=0; i < totalRem; i++)
{                           
strValor = objRemetente.options[i].text;
if (objRemetente.options[i].selected){                                                                    
strDes += "<option value='" + strValor + "'>" + strValor + "</option>";                           
}
Else
{                                      
  strRem += "<option value='" + strValor + "'>" + strValor + "</option>"                           
}               
 
}                              
 
strDes += "</SELECT>";               
strRem += "</SELECT>";
                              document.getElementById(tdDestino).innerHTML = strDes;               
document.getElementById(tdRemetente).innerHTML = strRem;                                          
sortSelect(document.getElementById(objRemetente.id), true);               
sortSelect(document.getElementById(objDestino.id), true);      
}    
</script>        
<body>   
 
<table width="100%" border="0" style="margin:100 1 1 1">               <tr>
<td width="33%" align="center" ></td>
<td width="34%">
<table width="100%" border="0">                                                  
<tr>                                                              
<td align="center" id="tdChildren">                                                                          
<SELECT id=cboChildren style="WIDTH: 130px; height: 100px" name=cboChildren multiple="multiple">
<option value="0">NY</option>                                                                                     
<option value="1">WS</option>                                                                                     
<option value="2">NC</option>                                                                                     
<option value="3">LA</option>                                                                                     
<option value="4">NE</option>                                                                                     
<option value="5">MI</option>                                                                                     
<option value="6">BO</option>                                                                          
</SELECT>  </td>   <td valign="middle" align="center">                                                                         
<input type="button" id="btnMoveRight" name="cboMoveRight" value=">>" onClick="onMoveItem(cboChildren, 'tdChildren', cboChildrenSel, 'tdChildrenSel');"/><BR />
<br />                                                                          
<input type="button" id="btnMoveLeft" name="cboMoveLeft" value="<<" onClick="onMoveItem(cboChildrenSel, 'tdChildrenSel', cboChildren, 'tdChildren');"/>
                                                              
</td>                                                              
<td align="center" id="tdChildrenSel">                                                                          
<SELECT id=cboChildrenSel style="WIDTH: 130px; height: 100px" name=cboChildrenSel multiple="multiple" height="200px">                                          
</SELECT>  </td>                                                  
</tr>                                      
</table>                           
</td>                           
<td width="33%">                                                       
</td>               
</tr>    
</table>    
</body>    
</html>


Listing 6 shows some code to force the user enters the correct information, which is the email field.

Listing 6. E-mail validation

<!DOCTYPE html>    
<html>    
<head>    
<script>               
function validateForm (){               
 
var x=document.forms["formValidate "]["email"].value;              
var atpos=x.indexOf("@");               
var dotpos=x.lastIndexOf(".");                   
 
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {                           
 
        alert("Invalid e-mail address!");                          
        return false;                 
}else{                           
        alert("Email address correct = "+x);                           
        return true;                 
}                   
}    
</script>    
</head>        
<body>               
 
<form name="formValidate" onsubmit="return validateForm();" method="post">                           
Email: <input type="text" name="email">                           
<input type="submit" value="Check e-mail address">               
</form>    
</body>    
</html>


Listing 7 show a simple example of how to validate the fields of a HTML form using the JavaScript language.

Listing 7. Field validation

<html>               
<head>                           
<title>Example script for field validation </title>                          
<script type="text/JavaScript">                                      
 
function validateFields (form) {                                                                                                   
 
//Get the id inside the form                                                  
var name = document.getElementById("name").value;                                                  
if (name == "") {                                                             
   alert("Type something for the field name!");                                                              
   form.name.focus();
                                                              
        return false;
}                                                                                                    
//Get the id inside the form                                                  
var age = document.getElementById("age").value;
                              
if (age == "" || !checkNumber(age)) {                                                              
alert("Use only alphanumeric characters!");                                    
form.age.focus();
 
return false;
  }                                                                                                    
//Check to see if the selected gender
if (form.gender[0].checked==false && form.gender[1].checked==false) {        
     alert("Choose a gender!");                                                              
      return false;                                               
    }                                               
 }                                                                            
// Function to check if the parameter is a number or not
function checkNumber (number)                                      
{                                         
var ValidateChars = "0123456789";                                         
var IsNumber=true;                                         
var Char;    
 
for (i = 0; i < number.length && IsNumber == true; i++)  {                                                     
        Char = number.charAt(i);                                                     
 
        if(ValidateChars.indexOf(Char) == -1) { 
             IsNumber = false;                   
          }                                                    
        }  
      return IsNumber;                                                          
}                                                                 
</script>               
</head>               
<body>                           
<form name="formCad" onsubmit="return validateFields(formCad)">
Type the name:                                       
<input id="name" type="text" size="12"/>                                      
<br />                                      
Type the age:                                      
<input id="age" type="text" size="5"/>                                      
<br />                                      
Gender:  <input type="radio" name="gender" value="0"> 
Male                                                     <input type="radio" name="gender" value="1"> 
Female
<br/><br/>                                      
<input type="submit" value="Save">                           
</form>               
</body>    
</html>


Elements behaviors and properties using DOM

There is a model of a generic object among the HTML, XML and JavaScript that helps the development of rich web applications: the DOM (Document Object Model).

Since the scripts are compliant with the W3C standard, they are compatible with on all major browsers, which provide a greater comfort for developers.

The DOM is a language-independent API that facilitates the manipulation of the structure of a document and the elements of HTML, XML, XHTML, and JavaScript pages. It also helps in the customization of elements in a complete way, enabling programs and scripts to dynamically access and update the content and style of a document.

This API provides two methods that are probably the most used in development. They are listed below:

  • document.getElementById (id) – Gets the element from the value of its id attribute. It is a good development practice to set an “id” property to HTML elements and only access them by the id. The null value is returned if the element does not exist on the page.
  • document.getElementByTagName (tag) - Gets a set of elements that are defined by a specific tag. This method returns an array containing all the elements on the page in the order they appear inside the HTML document.

Listing 8 shows an example where the elements access are made using the tag and the getElementByTagName() function.

Listing 8. getElementByName Function

<!DOCTYPE html>    
<html>    
<head>    
<script>               
function getElements()                 
{                             
//Get the elements by the tag                             
var x=document.getElementsByTagName("input");             
 
alert("Answer = "+x.length);                     
}    
</script>    
</head>    
<body>                   
<input type="text" size="20">
<br><input type="text" size="20">
<br><input type="text" size="20">
<br><br>
<input type="button" onclick="getElements()" value="Click to see how many input elements are inside this page">        
</body>    
</html>


When the DOM model is represented in an HTML document, the page can be represented as a hierarchy of elements in the form of a tree, i.e. each leaf in the tree represents a node which relates directly to each element on a page. At the time that a node appears under another node in the tree is a hierarchy built, which turns out to be considered a child of that node.

Each node in a DOM tree is classified according to its kind. The most important types are the element and text nodes.

  • Element - Any HTML element that matches a tag used inside the HTML.
  • Text - The text content for an element, which is always stored as a child node under an element.

In Figure 1 show an example of a DOM hierarchy. Listing 9 shows an code sample that represent the elements of hierarchy of Figure 1.

Figure 1. DOM tree with the HTML elements of Listing 9.

Listing 9. HTML elements of Figure 1.

<!DOCTYPE html>    
<html>               
<head>                           
<title>Page title</title>               
</head>               
<body>                           
<h1>Paragraph 1 
<h1>                           
<p> Paragraph 1 <em> with a text node </em> and back with the paragraph element </p>                         
<p>Paragraph 2</p>               
</body>    
</html>


Listing 10 shows the attributes of the HTML element known as "div". The content of this element is accessed by the "innerHTML" property.

Listing 10. Hierarchy of the “div” element.

<html>    
<head>   
<title> Hierarchy of the “div” element with JavaScript</title>
<script type="text/JavaScript">                       
function listAttributes ()
{                           
var elem = document.getElementById("div_element ");                           
var attr = "";   
 
for(var i = 0; i < elem.attributes.length; i++){                             
        attr += elem.attributes[i].nodeName + "<br>";                          
}                                                      
elem.innerHTML = attr;                 
}        
</script>    
</head>    
<body>                   
<div id="div_element" style="border: 1px solid red">
Inside the DIV element 
</div>                   
<button onclick="JavaScript:listAttributes()">
List the attributes of the DIV element
</button>        
</body>    
</html>


The source of the interactions with the DOM is the "document" object, which is a top node of the document’s node tree. This object provides two methods: getElementById() and getElementByTagName(), both already shown in previous scripts.

The following methods can be used to navigate through the document tree as well:

  • hasChildNodes - returns true if the element has children;
  • firstChild - returns a reference to the first child element;
  • lastChild - returns a reference to the last child element;
  • nextSibling - returns a reference to the next sibling element;
  • previousSibling - returns a reference to the previous sibling element;
  • nodeName - TAG returns the element’s name (only for node elements);
  • nodeValue - returns the element value (only for text elements);
  • nodeType - returns the element’s;
  • parentNode - returns a reference to the parent element.

Those are the key properties to manipulate the document tree and to access specific data node. Listing 11 shows an example of these properties used to retrieve information about each element inside the document.

Listing 11. DOM element’s properties.

<html>       
<head>          
<title>Properties of the elements of the DOM tree </title>
 
<script>             
//Global variables
var el;              
var nome;             
var tipo;             
var valor;                          
 
function start()             
{                 
el = document.documentElement; 
nome = document.getElementById("name"); 
tipo = document.getElementById("type"); 
valor = document.getElementById("value"); 
show();              
}                          
function show() // Show the information
{                 
        nome.value = el.nodeName;                
        tipo.value = el.nodeType;                
        valor.value = el.nodeValue;             
}                          
function restart() // Get the root node
{                
        el = document.documentElement;                
        show();             
}                          
function firstChild () // get the first child
{                 
if(el.firstChild)
        {                   
               el = el.firstChild;                  
               show();                 
}                 
else                    
        alert("The element does not have children !");               
}                          
 
function lastChild () // get the last chield
{                 
        if(el.lastChild){                   
               el = el.lastChild;                   
               show();                 }                 
        else                    
               alert("The element does not have children !");               
}                          
 
function getParent () // get the parente element
{                
        if(el.parentNode)
        {                   
               el = el.parentNode;                   
               show ();                 
        }                 
        else                    
               alert("The element does not have a parent!");               
        }                          
function nextSibling () // get the next sibling
        {                 
               if(el.nextSibling){                   
                       el = el.nextSibling;                   
                       show ();                 
        }                 
        else                    
               alert("The element does not have a next sibling!");               
}
 
function previousSibling () // get the previous sibling 
{                 
        if(el.previousSibling){                   
               el = el.previousSibling;                   
               show ();                 
}                 
else                   
        alert("The element does not have a previous sibling!");               
}                       
</script>                 
</head>              
<body>                    
<form>                
<fieldset>                   
<input type="button" name="next" value="Next Sibling" onClick="nextSibling();" />                   
<input type="button" name="prev" value="Previos Sibling" onClick="previousSibling ();" />                   
<input type="button" name="parent" value="Parent" onClick="getParent();" />                   
<input type="button" name="first" value="First Child" onClick="firstChild();" />                   
<input type="button" name="last" value="Last Child" onClick="lastChild();" />                   
<input type="button" name="restart" value="Restart" onClick="restart();" />                                                                    
<br/>
Value :<input type="text" name="value" id="value" value="" size="65" />    
<br/> Type: <input type="text" name="type" id="type" value="" />                   
<br/>                       
Element’s name:<input type="text" name="name" id="name" />                 
</fieldset>             
</form>     
<script language="JavaScript">       
start();// Start just after the loading of all elements
</script>           
</body>   
</html>   


We conclude this article stating that JavaScript is the language for whose want to manipulate the HTML internal elements and adapt the script code to other web frameworks and languages.



Front-end developer, WebEditor of MrBool.com and SEO Analyst. Work in the development area for over 4 years. For freelance work visit my portfolio: www.ricardoarrigoni.com.br

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login