Read, With the Name of Your Lord Who Created

Posts Tagged ‘DOM’

DOM & HTML Revisited

Posted by triaslama on April 18, 2008

What can I say about DOM (Document Object Model)? Its lightweight, its everywhere, its some kind useful. How about HTML? its everywhere and its easy. But, I think, the most important about them both is because both doesn’t suck!
I don’t know how about you. I just doing a simple (and I think interesting enough) exploration about HTML & DOM. Let’s check it out!

Suppose I want to make an element enabled & disabled when I select an item from a dropdownlist (combo box). With HTML it can be accomplished easily! How about if I want to make a new <select> element when I have choose something from previous <select> element?? With mix blend of DOM & HTML it can be accomplished easily too!

This page consist of two parts, each of them separated by horizontal lin. This is the screenshots of my simple page:
init
Initial condition, first part and second part separated by horizontal line.

Read the rest of this entry »

Posted in DOM, HTML / CSS, Javascript | Tagged: , , , , , | 1 Comment »

CRUD Operations Using DOM

Posted by triaslama on March 21, 2008

CRUD (Create, Read, Update, Delete) is common operations in data storage, but now I will try to use DOM (Document Object Model) doing CRUD operations toward document content (and I think that is one of DOM objective). DOM can be used for doing CRUD operations easily and effectively. OK that’s enough for the buzz words let’s make the job done!

1. Create an Element
To create an element use document.createElement(<elmName>) method. This method receives one parameter that is the name of element that will be created. DOM method document.createTextNode(<text>) is similar to document.createElement but will create a text node instead of an element. The parameter received by document.createTextNode is text that will be created. The other DOM method that important in creating an element is appendChild(<elem>), this method will append the element specified as parameter to an element. Below is an example of add a <li> element to a <ul> element:

var ul = document.getElementsByTagName("ul")[0];
var li = document.createElement("li");
var text = document.createTextNode("'li' element.");

li.appendChild(text);
ul.appendChild(li);

2. Read Text of an Element
Please pay a special attention that a text in DOM is considered as a node, so we have to navigate to its text node first before we retrieve / read the node value. So, if ‘elm’ is a variable that point to a <li> element the following code:
var text = elm.firstChild.nodeValue;

will retrieve the text inside a <li> element and store the value to a variable named ‘text’.

3. Update an Element Content
Update operation really similar to read operation, except updating an element means we change the node value with the new one. If ‘elm’ point to a <li> element, the following code:

var newValue = "New text node value";
elm.firstChild.nodeValue = newValue;

will change the node value inside <li> element with the content of ‘newValue’ variable.

4. Delete an Element
Here, delete an element has two meanings. First delete the text node inside an element, second delete the element itself. Deleting an element can be accomplished using removeChild(<elm>) method. This method receives one parameter, that is child element that will be deleted.
This line of code:
elm.parentNode.removeChild(elm);
will remove ‘elm’ element.

I have write a simple code that demonstrate how to create, read, update, and delete (CRUD) the document content using DOM. I use the Javascript events and blend it with DOM to accomplished CRUD operations, so basic understanding of Javascript events will really helpful.

The code consists of two portions, first portion is html code (crud.htm):

<html>
<head>
<title>CRUD Operations: Complete</title>
<script lang=”javascript” type=”text/javascript” src=”crud.js” >
</script>
</head>
<body>
Want to know why DOM is awesome??
One of the possible answer is: with DOM we can create, read (retrieve), update, and delete document content quickly and easily.
<p/>
<b>Try the following example!</b>
<br/>
<b>
1. Press ‘Add’ button to add a new <li> element.<br>
2. Move the mouse cursor over a <li> element below.<br>
3. Click desired <li> element to read the node value.<br>
4. Hold down ‘Shift’ key and click desired <li> element to update the node value.<br>
5. Hold down ‘Ctrl’ key and click desired <li> element to delete the <li> element.<br>
</b>
<p>
<form id=”frm” name=”frm” style=”background-color:yellow; border:solid 2px; border-color:goldenrod;”>
<ul><b> And here is the list of <li> element:</b>
<li>First li element.</li>
<li>Second li element.</li>
<li>Third li element.</li>
<li>Fourth li element.</li>
<li>Fifth li element.</li>
</ul>
<p>
<input type=”button” id=”btnCreate” onclick=”addLiElement()” value=”Add New <li> Element” />
<p>
</form>
</body>
</html>

The other one is Javascript code (crud.js, this code is referred by html code), and this is the Javascript code:


window.onload = handleCRUD;


function addLiElement()
{
// ask input text for new <li> element
var txt = window.prompt("Text: ");
var text = document.createTextNode(txt);
// create <li> element
var elm = document.createElement("li");
/* retrieve the first <ul> element (and the only one). */
var ul = document.getElementsByTagName("ul")[0]; elm.appendChild(text);
ul.appendChild(elm);

handleCRUD();
}


function handleCRUD()
{
var lis = document.getElementsByTagName("li");
for (var i=0;i<lis.length;i++) {
lis[i].onmouseover = function()
{
this.style.backgroundColor = "gainsboro";
};


lis[i].onmouseout = function()
{
this.style.backgroundColor = "yellow";
};

/* ‘click’ event handles read, update, or delete operation */

lis[i].onclick = function(e)
{
// IE handles event through window.event property
e = e||window.event;
/* again IE handles target (source) element as srcElement */
var elm = e.target||e.srcElement;
if (e.ctrlKey) {
/* because 'ctrl' key is pressed, it will be delete operation */
var txtNode = elm.firstChild;
// first, delete the text node
txtNode.parentNode.removeChild(txtNode);
// second, delete the <li> element
elm.parentNode.removeChild(elm);
return;
}
if (e.shiftKey) {
/* because 'shift' key is pressed, it will be update operation */
var newValue = window.prompt("Enter new value: ");
elm.firstChild.nodeValue = newValue;
return;
}
else {
/* neither 'ctrl' nor 'shift' key is pressed, it will be read
operation */
/* now, here we retrieve the content (text) of an element */
var content = elm.firstChild.nodeValue;
window.alert(content);
return;
}
};

}
};

The javascript code started with window.onload that executed after the document is loaded, and passed handleCRUD() function to it. Inside handleCRUD we install mouseover, mouseout, and click events foreach <li> element exist in document.

What is done by each event can be explained as follow:

  • ‘Add’ button onclick: adds an li element to the document.
  • onmouseover: changes the background color of a <li> element to ‘gainsboro’ when mouse cursor enters it.
  • onmouseout: restores the background color of a <li> element to ‘yellow’ when mouse cursor leaves it.
  • onclick, this event has three meanings:
    1. when we click an <li> element along with ‘Ctrl’ key pressed, then the specified <li> element will be deleted.
    2. when we click an <li> element along with ‘Shift’ key pressed, then the node value of specified <li> element will be updated.
    3. when we click an <li> element and neither ‘Ctrl’ key nor ‘Shift’ key is pressed then we simply read the specified <li> element.
  • onclick event handler receive one parameter that is event object (‘e’ in this code), but event object in Internet Explorer (IE) available through window.event property. So we need a regular checking ‘e’ will be still ‘e’ or if the browser is IE e will be filled with window.event.

    e = e||window.event;

    The target (non IE browser) / srcElement (IE) are properties of event object contains a reference to the element that fired to the event. We get target / source element with the following code:

    var elm = e.target||e.srcElement;

    This is screenshot output produced by crud.htm & crud.js:

    CRUD using DOM

    To make the same output as screenshot above puts crud.htm & crud.js in the same directory, type the location in address bar of your browser and you should see the same result.

    Thanks for your attentions, see you next time…

    Posted in DOM, Javascript | Tagged: , , , , , , , , | Leave a Comment »

    When Spaces Does Matter

    Posted by triaslama on March 12, 2008

    In this post I just want to talk about spaces, why spaces? Because it could be a matter especially when working with DOM (Document Object Model). Look at the following HTML code:

    <html>
    <head>
    <title>Test Spaces</title>
    <script lang=”javascript” type=”text/javascript”>
    var ul;
    var children;
    window.onload = function()
    {
    ul = document.getElementsByTagName(“ul”)[0];
    children = ul.childNodes;
    };
    document.onclick = function()
    {
    window.alert(“The number of ul’s children: “+children.length);
    };
    </script>
    </head>
    <body>
    <ul>
    <li>First Item</li>
    <li>Second Item</li>
    <li>Third Item</li>
    </ul>
    </body>
    </html>

    Now guess, when I run the code and click the document how many child belongs to ul in the code above? The answer may vary, if you run the code in Firefox 2 or Opera 9.01 browser the answer is 7, but in Internet Explorer 6 (IE6) the answer is 3! Why does it differ? The difference of answers because of spaces!

    As you’ll notice, between <ul> and first <li> element there is actually an end line which is considered as a white space. Also between first <li> and second <li>, between second <li> and third <li>, and the last between third <li> and close tag </ul> there is exist end line which considered as white spaces.

    White spaces become a matter because its representation in XML. Either Firefox or Opera represent a white space as a node but not in IE. So when we run the code in Firefox or Opera <li> element has 7 childs (four white spaces and three <li> elements).

    So far I found two solutions toward spaces problem. First we can skip it, so we need to change document.onclick function into the following:

    document.onclick = function()
    {
    var temp = 0;
    for (var i=0;i<children.length;i++) {
    if (children[i].nodeType == 1) {
    // do some interesting stuffs here…
    temp += 1;
    }
    }
    window.alert(“The number of ul’s children: “+temp);
    };

    Second we can remove it, so change the script into the following:

    var ul;
    var children;
    window.onload = function()
    {
    ul = document.getElementsByTagName(“ul”)[0];
    removeSpaces(ul);
    children = ul.childNodes;
    };
    function removeSpaces(elm)
    {
    for (var i=0;i<elm.childNodes.length;i++) {
    var child = elm.childNodes[i];
    if (child.nodeType==3 && /\s/.test(child.nodeValue))
    child.parentNode.removeChild(child);
    }
    }
    document.onclick = function()
    {
    window.alert(“The number of ul’s children: “+children.length);
    };

    Note: the code above only removes spaces at its current child element, so if <li> element has a child node another than text node, the spaces problem will still remain. We can skip it using first solution although it may impractical especially when our document tree quite large. The better solution I think using a recursive function that traverses the document tree and removes all spaces in document.

    Here I listed the nodeType property number and its corresponding type that I used in the preceding code:

    nodeType Number

    Type

    1

    Element

    2

    Attribute

    3

    Text

    4

    CDATA Section

    5

    Entity Reference

    6

    Entity

    7

    Processing Instruction

    8

    Comments

    9

    Document

    10

    Document Type

    11

    Document Fragment

    12

    Notation

    Posted in DOM, Javascript | Tagged: , , , | Leave a Comment »

    Sliding Div Using Javascript

    Posted by triaslama on February 28, 2008

    Javascript is useful, and in this post I will try to reveal the power of setTimeout one of the method of window object. This method allow us to execute a function after a specified time (in milliseconds). We will make a div element that can be collapsed or expanded dynamically by hitting a button, so lets start.

    Consider we have html page with a div element and a collapse/expand button inside it. The div element contains three buttons (each button will produce an alert, confirm, and prompt box respectively). The collapse/expand button expand / collapse the div element depends on the status of div element itself. Below is the screen shoot of our simple page:

    defaultdivslider3.jpg

    I hope the picture is self explanatory, by clicking the collapse button the div element will degrade and finally disappear. After the div element disappear the Collapse button will changed with Expand button. Clicking the expand button will show our div and it will expand dynamically until a specified size.

    Clicking one of three buttons inside div element will produce an alert or confirm or prompt box depends on what button we are clicked.

    So lets jump to the code! I split the code into two pieces -Html file (SlidingDiv.htm) and Javascript file (SlidingDiv.js)-. Here the HTML code:


    <html>
    <head>
    <title>Sliding Div HTML</title>
    <script lang="javascript" type="text/javascript" src="slidingdiv.js">
    </script>
    </head>
    <body>
    <div id="targetDiv" style="width:500px;height:250px;background-color:gainsboro; ">
    <center style="font-weight:bold" >Target Div</center>
    <p>
    <center>
    <input type="button" id="btnAlert" onclick="showAlert()" value="Alert" />
    <input type="button" id="btnConfirm" onclick="showConfirm()" value="Confirm" />
    <input type="button" id="btnPrompt" onclick="showPrompt()" value="Prompt" />
    </center>
    </div>
    <p>
    <input type="button" id="btnExpandCollapse" onclick="slideHandler()" />
    </body>
    </html>

    The above code simply produce an output like the screen shoot picture. Please notice that the code refers to a Javascript file named slidingdiv.js. And this is the Javascript code:


    var status;
    var height;
    var max;
    var min;


    // Initialize our variables here
    window.onload = function(){
    var temp = document.getElementById("targetDiv").style.height;
    height = parseInt(temp);
    status = 1;
    max = height;
    min = 60;
    document.getElementById("btnExpandCollapse").value = "Collapse";
    };


    function slideHandler()
    {
    if (status==0) {
    expand();
    status = 1;
    }
    else {
    collapse();
    status = 0;
    }
    }

    function collapse()
    {
    if (height>min) {
    height -= 1;
    document.getElementById("targetDiv").style.height = height;
    document.getElementById("btnExpandCollapse").disabled = true;
    window.setTimeout("collapse()", 1);
    }
    else {
    setButtonValue("Expand");
    document.getElementById("targetDiv").style.visibility = "hidden";
    }
    }


    function expand()
    {
    if (document.getElementById("targetDiv").style.visibility == "hidden")
    document.getElementById("targetDiv").style.visibility = "visible";
    if (height<max){
    height += 1;
    document.getElementById("targetDiv").style.height = height;
    document.getElementById("btnExpandCollapse").disabled = true;
    window.setTimeout("expand()", 1);
    }
    else {
    setButtonValue("Collapse");
    }
    }



    function setButtonValue(val)
    {
    document.getElementById("btnExpandCollapse").value = val;
    document.getElementById("btnExpandCollapse").disabled = false;
    }


    function showAlert()
    {
    window.alert("Alert...");
    }


    function showConfirm()
    {
    window.confirm("Confirm?");
    }


    function showPrompt()
    {
    window.prompt("Prompt: ");
    }

    The Javascript code start with variables initialization, and the initialization accomplished inside anonymous function that passed in window.onload. The window.onload happen when html element has finished to be rendered.

    There are several variables that need to be initialized. Status variable indicate the ‘div’ element status, if status=1, ‘div’ element is visible and value of expand/collapse button is ‘Collapse’. If status=0 ‘div’ element is hidden and value of expand/collapse button is ‘Expand’. Temp variable holds the height of ‘div’ element. After the value of temp parsed to integer its value preserve in height variable. Don’t forget to parse the value that retrieved from height property of targetDiv to integer, because this value actually not a number! So parse this value to integer first to make it work!

    Function slideHandler() called every time we clicked expand/collapse button, if status is ‘0’ the ‘div’ will be expanded and status changed to 1. If status=1 ‘div’ element will be collapsed and status changed to 0.

    Function collapse() will collapse ‘div’ element with the sliding effect, then if the height<min we set the visibility of div element to ‘hidden’. Function expand() will expand ‘div’ element with the sliding effect, but first we need to set visibility of ‘div’ element to ‘visible’. Actually what makes the sliding effect work is the window.setTimeout() function!

    window.setTimeout() receives two parameter, first parameter is the name of function that will be executed after a specified delay of time, second parameter is delay of time (in milliseconds). In our case window.setTimeout() called inside expand() and collapse() function.

    Inside collapse() function the value of height variabel decrement by one and its value send to height property of ‘div’ element. After that we disabled the expand/collapse button and call window.setTimeout() with delay one millisecond and passed collapse() as function that will be executed after elapsed delay. In the other words its recursive! The recursive call will end if height less than min (in this case we set the expand/collapse button value to ‘Expand’ and visibility of ‘div’ element to hidden). Setting div visibility to hidden automatically also hidden controls that placed inside ‘div’ element.

    The expand() function work in similar way but we increment the height value by one, and passed expand() as first parameter of window.setTimeout(). Collapse function also set the visibility of ‘div’ element to visible if it was hidden. In the end of recursive call inside expand we set the value of expand/collapse button to ‘Collapse’.

    The others should be work as it is so I think it doesn’t need explanations. I hope this useful.

    Thanks and regards, Tri Sugiyantowo.

    Posted in DOM, Javascript | Tagged: , , , , | 9 Comments »

    Javascript: Adding OnMouseOver And OnMouseOut Using DOM

    Posted by triaslama on February 2, 2008

    The DOM (Document Object Model) is a standard way to access a document within a browser. The DOM could be Core DOM, HTML DOM, XML DOM. The DOM can be very handy and useful when we need to access the specific elements of the document and add some effects to them.

    The two of the most useful of the DOM methods could be getElementById and getElementsByTagName. The getElementById will return an element that specified as a parameter in getElementById DOM method. The parameter that passed is a string that represents the ID of an element. The getElementsByTagName -that receive one parameter, the element name as string- will return array that represents elements in the document with the tag name specified as a parameter in getElementsByTagName method.

    Here a simple example utilization of getElementById and getElementsByTagName method to add an effect -change the background color- when the mouse cursor over a <li> element and reset the background color when then mouse cursor out a <li> element:

    SimpleDom.htm

    <html>
    <head>
    <title>Test Something</title>
    <script lang=”javascript” type=”text/javascript”>
    window.onload = function()
    {
    var lis = document.getElementsByTagName(“li”);

    for (var i=0;i<lis.length;i++) {
    lis[i].onmouseover = function()
    {
    this.style.backgroundColor = “gainsboro”;
    };
    lis[i].onmouseout = function()
    {
    this.style.backgroundColor = “white”;
    };
    }
    };
    </script>
    </head>
    <body>
    <ul>
    <li>First Element</li>
    <li>Second Element</li>
    <li>Third Element</li>
    </ul>
    </body>
    </html>

    Let’s look at the code in more details. The body of the document consist of an unordered list (ul). The <ul> element have three list item <li> element as childs. The scenario is simple change the background color of <li> element when the mouse is moved over around them and reset the background color of <li> element when the mouse is moved out of them.

    To attain this functionalities we using Javascript and DOM to access the document specified in the <body> element. The first line of our Javascript code is window.onload, this function is executed when the window object is fully loaded, in the other word the window.onload executed only when the elements inside a document has been rendered.

    To handle window.onload we create an inline function that tells what must be done when the page has been loaded. In this case we will retrieve all of <li> element in a document using getElementsByTagName DOM method and save this element in a variable named lis.

    var lis = document.getElementsByTagName(“li”);.

    The next step iterate through all of <li> element inside lis variable:

    for (var i=0;i<lis.length;i++).

    But the most important part here we install two events for each of <li> element, onmouseover (happens when the mouse cursor over an <li> element) and onmouseout (happens when the mouse cursor out from an <li> element).

    To handle the onmouseover event we create an inline function that changes the background color of <li> element when the mouse cursor over it.

    lis[i].onmouseover = function()
    {
    this.style.backgroundColor = “gainsboro”;
    };

    To handle event when the mouse cursor out of an <li> element we create an inline function that reset the background color back to its original color.

    lis[i].onmouseout = function()
    {
    this.style.backgroundColor = “white”;
    };

    The word this above refers to the <li> element that being iterated. When everything is ready and we move the cursor over an <li> element we should see that the background color of <li> that is being hovered change to gainsboro, and the background color will back to white when the mouse cursor leaves the specified <li> element.

    The Javascript and DOM can have more functionalities and usages I hope this simple article will give me and all the readers a clue about the advantage of DOM.

    Posted in DOM, Javascript | Tagged: , , , , , | 27 Comments »