JavaScript Tutorial

How to trim string value :: JavaScript Tutorial

Posted on

hi all..
hope everything is good at your end ..
today, there is a smal tip for javascript users …
umm infact not a tip but a utility function to trim string values ..
i was working on a project i had a need to trim user input befor submitting to server side
here is the quick way to do this .
<script type=”text/javascript” language=”javascript”>
function trim(paramString){
return paramString.replace(/^\s*/, “”).replace(/\s*$/, “”);
and thats it …
happy development 🙂

free counters


Event Object :: JavaScript Tutorial

Posted on Updated on

Hello All …

Hope enjoying most enjoyable activity .i.e development 🙂 i love it … really love it ..

Today i will try to explain something related to javascript event object. By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.

Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

Examples of events:

  • A mouse click
  • A web page or an image loading
  • Mousing over a hot spot on the web page
  • Selecting an input field in an HTML form
  • Submitting an HTML form
  • A keystroke

Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!

I will give you some example scripts for reading out event properties. There are very serious browser incompatibilities in this area.

As soon as we want to read out information about the event, we’re inundated by an immense amount of properties, most of which do not work in most browsers. See the Event compatibility tables for a quick overview or the W3C DOM Compatibility – Events page for a complete overview.

I am not going to give an alphabetical list of properties, since it wouldn’t help a bit to make you understand all this — the situation is too confusing. Instead I’ve written five scripts to ask five questions of the browser.

  1. What is the type of the event?
  2. Which HTML element is the target of the event?
  3. Which key was pressed during the event?
  4. Which mouse button was pressed during the event?
  5. What was the mouse position during the event?

Please note that in these scripts I’ve been very strict in my object detection. I first create cross-browser event access, then I check if the browser supports each individual property before using it.

What is the type of the event?

This is the only question with a true cross-browser answer: use the typeproperty to read out the type:

function doSomething(e) {
	if (!e) var e = window.event;

Which HTML element is the target of the event?

W3C/Netscape says: the target. No, says Microsoft, the srcElement. Both properties return the HTML element the event took place on.

function doSomething(e) {
	var targ;
	if (!e) var e = window.event;
	if ( targ =;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

The last two lines of code are especially for Safari. If an event takes place on an element that contains text, this text node, and not the element, becomes the target of the event. Therefore we check if the target’snodeType is 3, a text node. If it is we move to its parent node, the HTML element.

Even if an event is captured or bubbles up, the target/srcElement always remains the element the event took place on.

Other targets

There are some more targeting properties. I discuss currentTarget on the Event order page and relatedTargetfromElement and toElement on the Mouse events page.

Which key has been pressed?

This one is relatively easy. First get the code of the key (a = 65) from thekeyCode property.

When you’ve read out the key code, send it through the methodString.fromCharCode() to obtain the actual key value, if necessary.

function doSomething(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);
	alert('Character was ' + character);

There are some subtleties that may make the key events hard to use. For instance, the keypress event fires as long as the user keeps the key pressed. However, in most browsers the keydown event also keeps firing as long as the key is pressed. I’m not sure this is a good idea, but it’s what happens.

Which mouse button has been clicked?

There are two properties for finding out which mouse button has been clicked: which and button. Please note that these properties don’t always work on a click event. To safely detect a mouse button you have to use the mousedown or mouseup events.

which is an old Netscape property. Left button gives a value of 1, middle button (mouse wheel) gives 2, right button gives 3. No problems, except its meager support (and the fact that it’s also used for key detection).

Now button has been fouled up beyond all recognition. According to W3C its values should be:

  • Left button – 0
  • Middle button – 1
  • Right button – 2

According to Microsoft its values should be:

  • Left button – 1
  • Middle button – 4
  • Right button – 2

No doubt the Microsoft model is better than W3C’s. 0 should mean “no button pressed”, anything else is illogical.

Besides, only in the Microsoft model button values can be combined, so that 5 would mean “left and middle button”. Not even Explorer 6 actually supports this yet, but in the W3C model such a combination istheoretically impossible: you can never know whether the left button was also clicked.

In my opinion W3C has made some serious mistakes in defining button.

Right click

Fortunately you most often want to know if the right button has been clicked. Since W3C and Microsoft happen to agree on this one and givebutton a value of 2, you can still detect a right click.

function doSomething(e) {
	var rightclick;
	if (!e) var e = window.event;
	if (e.which) rightclick = (e.which == 3);
	else if (e.button) rightclick = (e.button == 2);
	alert('Rightclick: ' + rightclick); // true or false

Please note that, although Macs have only one mouse button, Mozilla gives a Ctrl–Click a button value of 2, since Ctrl–Click also brings up the context menu. iCab doesn’t yet support mouse button properties at all and you cannot yet detect a right–click in Opera.

Mouse position

As to the mouse position, the situation is horrible. Although there are no less than six mouse coordinates property pairs, there is no reliable cross–browser way to find the mouse coordinates relative to the document we need.

These are the six property pairs — see also the Event compatibility tables or the W3C DOM Compatibility – Events page.

  1. clientX,clientY
  2. layerX,layerY
  3. offsetX,offsetY
  4. pageX,pageY
  5. screenX,screenY
  6. x,y

I explained the problem, W3C’s vagueness and the use of pageX/Y andclientX/Y in my slightly outdated Evolt article.

The screenX and screenY properties are the only ones that are completely cross–browser compatible. They give the mouse position relative to the entire computer screen of the user. Unfortunately this information is completely useless: you never need to know the mouse position relative to the screen — well, maybe only if you want to place another window at the mouse position.

The other three property pairs are unimportant. See the W3C DOM Compatibility – Events page for a description.

Correct script

This is the correct script for detecting the mouse coordinates:

function doSomething(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	// posx and posy contain the mouse position relative to the document
	// Do something with this information

happy development 🙂 have nice time …

free counters

Document Object Model :: JavaScript Tutorial

Posted on Updated on

Hello All …

Hope everything is going good at your end …

today we will explore something about Document Object Model (DOM). From last few days i’m working on javascript and hence i read some good articles about script and dom…i learned alot and now sharing with you …


The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

With the Document Object Model, programmers can build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions

The DOM is a programming API for documents. It is based on an object structure that closely resembles the structure of the documents it models. For instance, consider this table, taken from an HTML document:

<TD>Shady Grove</TD>
<TD>Over the River Charlie</TD>

graphical representation of the DOM of the example table

What is DOM Tree

Consider the following code 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>

In your browser, this renders as this (hold your mouse over the paragraph to see the title – most browsers display it as a tooltip, some display it in the status bar):

This is a sample of some HTML you might
in your document

The DOM tree views this (simplified) as follows:

                              |                              |
                          childNodes                    attributes
                ______________|___________                   |
               |              |           |            title = 'The test paragraph'
'This is a sample of some '   B   ' in your document'
                   |          |       |
           'HTML you might'   BR   'have'

Of course, the tree also extends above the ‘P’ from window.document, through the HTML element, down through the body element, then through any other container elements to the paragraph.

The parts of the DOM tree are known as nodes. The ‘P’, ‘B’ and ‘BR’ nodes are element nodes, childNodesand attributes are collections, the title='The test paragraph' pair is an attribute node, and the text strings are text nodes.

Referencing the element nodes

Using the DOM, there are several ways that we could reference the paragraph. We can use getElementsByTagName to reference all paragraphs, then choose the one we want. If the paragraph were to be given an id, we could also use getElementById:

document.getElementById('id of paragraph')

If we assigned the paragraph an id so that we could use getElementById, the id='elementID' pair would appear in the attributes collection, along side title='The test paragraph' in the tree diagram above. Note that if the document is served with an XML based content-type header, getElementsByTagNamebecomes case sensitive.

NOTE: getElementsByTagName does not return a true collection, it returns an object with element index and ‘length’ properties. This object keeps itself up to date, so if an element it references is deleted or added, it will automatically change its item references to reflect that change.

We could even walk the entire DOM tree from the document object, for example:


In this case, window.document.childNodes[0] should be the HTML element, as it is the first tag in the document (assuming there is no doctype tag), and window.document.childNodes[0].childNodes[1]should be the body tag, as the head element will be the first child of the HTML element. Alternatively, there is a shortcut to the HTML element: document.documentElement so we could use this:


There is also a shortcut to the BODY element: document.body so we could use this:


Those last three examples are based on a simple page structure, where the paragraph is a direct child of the body element. Neither of these would be correct in the current document as the document structure is far more complex, also using DIV elements as parents of the paragraph.

The techniques used in those examples can be unreliable. Most browsers will correctly view the blank space between tags as a text node containing only white space characters (such as space, line-break or tab), even if the blank space is not rendered, such as a gap in between a tag or a blank gap in betweentags. However, some browsers (mainly Internet Explorer) will not view this empty space as a text node at all.

This means that the childNodes collection will be different lengths in these different browsers. If you are trying to walk the DOM tree to the next element node, for example, it may be worth checking each entry in the childNodes collection to see if its nodeType is 1, or to use node.getElementsByTagName.

Because of this, and the fact that the structure of the DOM tree is designed to change as elements are moved, added or removed, the only reliable way to reference an element is using its ID:

var theParagraph = document.getElementById('id of element')

The first entry of the childNodes collection can be accessed using the shortcut firstChild, and the last can be accessed using lastChild. node.nextSibling references the next entry in the parent node’s childNodes collection and node.previousSibling references the previous one. To reference the parent node, we use node.parentNode. Note also that all element nodes have the getElementsByTagName method to help reference elements within them. This means that from any node, it is possible to reference any of the other notes around it.

Referencing the attribute node

To reference the title=’The test paragraph’ attribute pair, we use the attributes collection. Depending on the browser, this collection may be filled up in a variety of different ways, and many empty attribute pairs may exist in the collection. To find the correct attribute, we search through the attributes collection for an attribute whose nodeName matches what we want. The nodeName may be in any case in HTML documents (typically upper case) and should be case sensitive in XHTML and XML if served using an XML based MIME type.

for( var x = 0; x < theParagraph.attributes.length; x++ ) {
  if( theParagraph.attributes[x].nodeName.toLowerCase() == 'title' ) {
    window.alert( 'The value of the \'title\' attribute is: ' +
      theParagraph.attributes[x].nodeValue );

An easy way to check the attribute node

If all you want to do is to check the value of an attribute, not manually edit its entry, it is easier to just use getAttribute.

window.alert( 'The value of the \'title\' attribute is: ' +
  theParagraph.getAttribute('title') );

Attribute names are case sensitive. For example, bgcolor must be written as bgColor.

Note that according to the specification, getAttribute should always return a string. However, this makes it impossible to differentiate between empty attributes and unspecified attributes. For this reason, browsers will return null for unspecified attributes, even though this is wrong. Opera 7-8 returns an empty string – this was changed to null in Opera 9. As a result, code that checks for attributes and incorrectly tests against null will fail in Opera 7 and 8, because a string will never equate to null. There is no need to test against null, just check if get attribute failed to retrieve a value:


Changing the attribute

The attributes of an element can be set or changed using setAttribute:


Attribute names are case sensitive. For example, bgcolor must be written as bgColor.
You can also remove attributes, with a few exceptions, using removeAttribute:


The event handler attributes are available as referenced functions (this is not the case for handlers added using DOM events), with their names matching the attribute name; element.onclick. These are read/write but must be written as a reference to a function, not as a direct string. They can also be written as a string using the Function constructor:

element.onclick = new Function(codeAsAString);

They may also be read as a string using the toString method of the function, but note that it will normally contain the anonymous function wrapper, and may not be available at all in browsers running on devices with limited capabilities, such as mobile phones. Note also that it will not be available at all if the attribute is not present:

var functioncode = element.onclick.toString();

The string value of the style attribute is available as a read/write string called cssText, which is a property of the style object, which itself is a property of the element. Note, however, that it is not supported very well; Safari does not support it up to version 1.1 (reading it produced the value null), Mozilla versions prior to 1.0 could not write to it, and iCab 3-, NetFront and Escape/Evo do not support it at all. To avoid problems with its use, a combination of cssText and getAttribute/setAttribute can be used. To read it:

var cssString;
cssString =;
if( typeof(cssString) != 'string' ) {
  cssString = element.getAttribute('style');

To write it, simply set both versions, and the browser will use whichever one works:

var cssString = 'color:lime;font-weight:bold;'; = cssString;

Note that this will then prevent it from being read correctly if other styles are changed individually. If this will cause a problem, check if cssText is supported first:

var cssString = 'color:lime;font-weight:bold;';
if( typeof( == 'string' ) { = cssString;

Referencing the text nodes

To give a full example, I will try to reference the text node ‘HTML you might’. To do this, I will go through the second entry of the childNodes array of the ‘P’. This will be a reference to the ‘B’. I will then look at the firstChild (equivalent to the first entry in the childNodes collection) of the ‘B’ to reference the text node.

window.alert( 'The value of the text node is:\n' +
  theParagraph.childNodes[1].firstChild.nodeValue );

Also important to note is that although the specifications say that no matter how much text exists between tags, it should all be in one text node, in practice this is not always the case. In Opera 7-9.2x and Mozilla/Netscape 6+, if the text is larger than a specific maximum size, it is split into multiple text nodes. These text nodes will be next to each other in the childNodes collection of the parent element.

In Opera 7-9.2x, this maximum text node size is 32 KB. In Mozilla/Firefox/Netscape 6+, it is 4 KB. Although the normalize() method of the parent node(s) should be able to replace the multiple text nodes with a single text node containing all the text, this only works in Mozilla/Firefox/Netscape 6+. In Opera 7-9.2x it puts all of the text into a single node and then truncates that node to 32 KB, so the contents of all except the first node are lost. Running the normalize method can crash Internet Explorer 6 and does not exist in Internet Explorer 5 on Windows.

For this reason, I do not recommend trying to normalize. It is better to manipulate the contents of text nodes separately. In fact, you can create your own text nodes and add them to the childNodes collection. Although to the DOM, they will still appear as separate nodes, they will appear as a single piece of text in the document. Basically, you need to be aware that your text may be split into several nodes, if it is 4 KB or over, or if you have added extra text nodes in yourself. In order to get that text in a single variable, you may need to look through every child node, and if they are consecutive text nodes append them together to get the total string.

Creating new nodes and removing existing ones

This is what the DOM was truly created for. In order to create new nodes, we use a couple of methods of the document object to create the node. We then insert the node into the main DOM tree, at which point the browser will display it. We can also move existing nodes (like the test paragraph) simply by inserting them into the DOM tree somewhere else.

Note that when creating element nodes, the element name must be in lower case. Although in theory it should not be case sensitive with HTML, I have noticed some problems in Konqueror when using upper case with strict doctypes – see the top of this page. It will be case sensitive with XHTML (in all compliant browsers, not just Konqueror), and must be in lower case.

var theNewParagraph = document.createElement('p');
var theTextOfTheParagraph = document.createTextNode('Some content.');

We could also use insertBefore instead of appendChild, or even manually add the new element to the end of the end of the childNodes collection. Using replaceChild, we could also overwrite existing nodes. It is also possible to copy a node using cloneNode(true). This returns a copy of the node but does not automatically add it into the childNodes collection. Using element.removeChild(referenceToChildNode), we can remove existing nodes.

How about something even more complicated. What about adding HTML elements within the new element, instead of just plain text. Here, I will recreate the test sentence from above, one piece at a time.

//three elements are required: p, b, br
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');

//set up theNewParagraph
theNewParagraph.setAttribute('title','The test paragraph');

//prepare the text nodes
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');

//put together the bold bit

//put together the whole paragraph

//insert it into the document somewhere

n case you were wondering how I managed to make those new paragraphs end up just above the links you clicked on, this is how.

The link you clicked on is in a paragraph. The paragraph is in a div (although this technique would work anywhere). The script is run in the event handler for the link. Therefore, in the handler function, ‘this’ refers to the link. The parentNode of the link is the paragraph – this.parentNode – and the parentNode of the paragraph is the div – this.parentNode.parentNode. I want to get the div to import the new paragraph node I have created above the paragraph the link is in, so I want to say this:


In JavaScript, this would be:


As for making them disappear when you click on them, when creating these paragraphs, I also assign an onclick event handler function that uses this.parentNode to reference the div, and then uses removeChild to delete the paragraph:

theNewParagraph.onclick = function () { this.parentNode.removeChild(this); };

Note that nodes belong to the document they were created in. So for example, if your page uses frames, and you create a paragraph node in one frame then attempt to add it to the document in another frame, it will not work. In theory you can use the document.importNode method to create a copy of it in the new document, but that method does not exist in Internet Explorer. If a script in one frame needs to create a node and append it to a document in another frame, it must use the document object for the destination frame when creating the node:

var newP = parent.frames['leftfr'].document.createElement('p');

Using document fragments

It is also possible to deal with multiple nodes at the same time. Say for example that you want to create 10 paragraphs, and add them all to the document at the same time as each other, instead of one at a time. This can be done using a document fragment. The benefit of using this is that it creates fewer document reflows, and as a result it can improve performance for big changes.

A document fragment is like a normal element (such as a div), except that it cannot become a part of the document itself. If you try to append a document fragment to any part of a document, instead of appending the fragment, the browser will add the child nodes of the fragment. For example, you create 10 paragraphs, append them to a document fragment, then append the document fragment to the body of a document. Instead of appending the fragment to the body, it will add the 10 paragraphs as children of the body.

var frag = document.createDocumentFragment();
for( var i = 0, p; i < 10; i++ ) {
  p = document.createElement('p');
  p.appendChild(document.createTextNode('Paragraph '+(i+1)));

There is still lot lot more to discuss but can’t do this on single post. I will post some more articles related to this topic to cover those things. I love javascript its really fun to play with dom …

Happy Development ..

free counters