Custom Search

Friday, November 27, 2009

JavaScript Note -1

JavaScript Note -1
====================================================1
JavaScript "TextField" and "Radio Button" Validation
---------------------------------------------------------------------------
<script language="JavaScript">
<!-- start script here
function checkform(thisform)
{
if (thisform.name.value == null || thisform.name.value == "")
{
alert ("Please enter your name");
thisform.name.focus();
thisform.name.select();
return false;
}
var selected = false ;
for (var i = 0; i <= 2 ; ++i)
{
if (thisform.gender[i].status == true)
{
selected = true;
}
}
if (selected == false)
{
alert ("Please choose your sex");
return false;
}
return true;
}
// End of script -->
</script>

--------------------------------------------
</head>
<body>
<h1>Registration Form</h1>

<form action="/cgi-bin/register.cgi" method="post"
enctype="multipart/form-data" onsubmit="return checkform(this)">
<table>
<tr>
<td align="right" class="required"><b>Name:</b></td>
<td><input name="name" class="required" /></td>
</tr>
<tr>
<td align="right" class="required"><b>Gender:</b></td>
<td class="required">
<input type="radio" name="gender" value="male" /> male
<input type="radio" name="gender" value="female" /> female</td>
</tr>
<input type="submit" value="register" class="submit" />
</td>
</tr>
</table>
</form>
</body>
</html>

====================================================2
Creating an Image Rollover
----------------------------------------------
<html>
<head>
<title>JavaScript Rollover Example</title>
<script type="text/javascript" language="JavaScript">
<!--
// Preload the images for the rollover

if (document.images) {
buttonOn = new Image();
buttonOn.src = "on.gif";
buttonOff = new Image();
buttonOff.src = "off.gif";
}

// Function to replace the off images with on images.

function activate(image_name) {
if (document.images) {
document[image_name].src = eval(image_name + "On.src");
}
}

function deactivate(image_name) {
if (document.images) {
document[image_name].src = eval(image_name + "Off.src");
}
}
// -->
</script>
</head>
<body>
<a href="rollover.html" onmouseover="activate('button')"
onmouseout="deactivate('button')"><img name="button" border="0"
height="100" width="100" src="off.gif"></a>
</body>
</html>


====================================================3
DOM
---------
Modern web browsers create a representation of a page that can be accessed via scripts in a standardized fashion. This representation is called the Document Object Model, or DOM. Under the DOM, the page content is treated as a tree of objects. I'm using the word objects the way a software developer would. In that parlance, an object is a component that generally has different “properties”, “methods”, and “event handlers”. A property is data that somehow describes the object. A method is a function you can call to make the object do something or to manipulate the object itself. An event handler is a hook you can use to enable the object to respond to an action (generally an action performed by the user). If you were speaking grammatically, you'd say that properties are an object's nouns and methods are its verbs.
----------------------------------------------------------
DOM Data Types
-------------------
When a DOM representation of a web page is created, all of the objects that are used to construct the page are assigned to various categories, which are called “interfaces” in the world of object-oriented programming. If an object has a certain interface then it has the properties and methods associated with that interface. For example, all of the tags on a page have the “element interface”, which means that they support methods such as getAttribute and setAttribute.
Interfaces in the DOM

Data Type Purpose
---------------------
document This is the root object in the DOM.
node All of the other interfaces mentioned are children of the node interface, and express all of its properties and methods.
element All the tags on a page express the element interface, and thus inherit all its properties, methods, and event handlers.
nodeList An array (or list) of elements. Some method calls return lists of elements. For example, you can fetch all the items in a list or all the children of any element. The results are returned in a nodeList.
attribute Attributes of tags have their own interface.
NamedNodeMap An alternative form of list for dealing with groups of elements.

-----------------------------------------------------------
The base of the DOM tree is the “document” object. You can call methods of the document object directly, such as document.write() to add content to the page, or you can reference children of the document object, using methods such as getElementById() or getElementsByTagName().

Another object that you'll deal with frequently is “window”. The “window” object (unlike document) is not formally part of the DOM, but browsers include it in order to provide an interface to the browser itself. For example, the height and width of the browser window are properties of the window object rather than the document object.

Using generic methods, you can get to all the children of the document object, but a number of convenience methods are included to give you shortcuts to things such as the forms, images, and links on a page.

-------------------------------Example
In this example, we're going to create a web page that enables us to manipulate elements on a page in various ways using the DOM. This example will work in any modern browser that supports the DOM.
<html>
<head>
<title>DOM Example</title>
<script language="JavaScript">

function changeBgColor(newColor)
{
if (document.body)
{
eval('document.body.bgColor="' + newColor + '"');
}
}

function tackOn(headingText)
{
if (document.body)
{
if (headingText)
{
var newHeading = document.createElement("h1");
someText = document.createTextNode(headingText);
newHeading.appendChild(someText);
document.body.appendChild(newHeading);
}
}
}

function setHeadingColors()
{
var headings = document.getElementsByTagName("h1");

for (var i = 0; i < headings.length; i++)
{
headings.item(i).style.color = "yellow";
}
}

</script>
</head>
<body>

<form>
Background color:
<select onchange="changeBgColor(this.options[this.selectedIndex].value);">
<option value="white">white</option>
<option value="red">red</option>
<option value="blue">blue</option>
</select><br />

Add heading:
<input type="text" value="Spam" id="newHeading" />
<input type="button" value="tack it on"
onclick="tackOn(document.getElementById('newHeading').value);" />
<br />
<input type="button" value="change colors"
onclick="setHeadingColors();" />
</form>

</body>
</html>

Let me describe quickly how the page works. The form on the page enables you to change the page's background color, add new headings to the page, and set the color of all the headings currently on the page to yellow. We accomplish this using three JavaScript functions and five form fields.
====================================================4
Cross-Browser DHTML Techniques
--------------------------------------------------
The most common technique for creating cross-browser DHTML was detecting the user's web browser (commonly called sniffing). After you determined which browser the user was using, you could simply execute the code tailored to that browser.

Here's a relatively simple browser sniffer that detects only Netscape Navigator 4 and Microsoft Internet Explorer 4 and up.
The following example shows the browser sniffer in action. The body element of the web page calls the doSniff function, which in turn, creates a variable called sniff and assigns it a string value to display, depending on the browser version it detects.

<html>
<head>
<title>Browser Sniffing</title>
<meta http-equiv="Content-Script-Type" content="text/javascript" />

<script language="javascript" type="text/javascript">
<!-- Hide JavaScript

// Trimmed down browser sniffer that
// detects Navigator 4+ and IE 4+.
// Reference is_nav4up and is_ie4up in other
// portions of the script.
var agt = navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
&& (agt.indexOf('Webtv')==-1));
var is_nav4up = (is_nav && (is_major >= 4));
var is_ie = (agt.indexOf("msie") != -1);
var is_ie4up = (is_ie && (is_major >= 4));


// Function to display the browser version
function doSniff() {
var sniff
if (is_nav4up == true) {
sniff = "Netscape Navigator 4+" }
if (is_ie4up == true) {
sniff = "Microsoft Internet Explorer 4+" }
alert(sniff);
}
// end hide -->
</script>
</head>
<body onload="doSniff()">
</body>
</html>

There are several big problems with relying on browser detection to make sure that your scripts work across multiple browsers. When new browsers are released, you have to go back through all your scripts that include browser detection and update them to account for the new browsers. Another problem is that if a browser you didn't account for supports the features included on your page, you might be denying access to people for no reason. Before you call a particular piece of code, you just have to test whether the browser supports the objects associated with the code you're calling.

====================================================5
Using JavaScript to Manipulate Elements
-----------------------------------------------------------------
In the world of Dynamic HTML, one of the most important tags you'll use is <div>. This tag is just a container into which you can put other elements. It's perfect because it enables you to group together some elements without any extra formatting baggage.

Once you've placed content within a <div> (or any other block level element), you can use JavaScript to manipulate its properties in the same way you set those properties when the page is displayed using CSS.
---------------------------------------------
One CSS property that is “visibility”,the two values for this attribute that you'll use are “hidden” and “visible”. Manipulating this property using JavaScript enables you to hide or reveal elements on a page.
I'm going to modify a page with the two overlapping elements so that if you click on one of the menus of links, the other is hidden.

<script language="JavaScript">
function hideMenu(idToHide)
{
if (document.childNodes)
{
document.getElementById(idToHide).style.visibility = 'hidden';
}
}
</script>

In the “hideMenu()” function, we first test for the presence of “document.childNodes”, which indicates that the browser has DOM support. If it does, we use “document.getElementById” to get a reference to the menu we want to hide, and I set the 'visibility' property to 'hidden'.


-------------------------------------------------------------
Creating a DHTML Pull-Down Menu
-----------------------------------------
It is possible to position elements on a page in a specific spot using style sheets. After they're positioned, you can move them around the page using JavaScript.
In this case, we've created a navigation bar across the top of the page. When the user puts the mouse pointer over the button in the navigation bar, the menu appears (and the button is highlighted). As long as the mouse pointer is over the button or the menu, the menu is displayed. Once the user removes the pointer, the menu will disappear after a 1-second delay.
<head>
<title>DHTML Test</title>
<script language="JavaScript">
function highlightAndPersist(button)
{
button.style.backgroundColor = '#ffc';
persist();
}
function unhighlight(button)
{
button.style.backgroundColor = '#ccf';
}

function persist()
{
var menu = document.getElementById('menu');
var button = document.getElementById('linkbutton');
menu.style.position = 'absolute';
menu.style.top = (button.offsetTop + button.offsetHeight) + 'px';
menu.style.left = (button.offsetLeft) + 'px';
menu.style.visibility = 'visible';
}

function hideSoon()
{
setTimeout("hide()", 1000);
}

function hide()
{
var menu = document.getElementById("menu");
menu.style.visibility = "hidden";
}
</script>

<style type="text/css">
body { margin: 0px; }
#menu
{
font-family: Verdana, sans-serif;
padding: 10px;
border: 1px solid black;
background-color: #ffc;
width: 150px;
visibility: hidden;
position: absolute;
top: 0px;
left: 0px;
}

#navbar
{
font: 18px Verdana, sans-serif;
width: 100%;
height: 30px;
background-color: #ccf;
padding: 0px;
}

.button
{
width: 80px;
height: 30px;
text-align: center;
}

p { margin: 10px; }
</style>
</head>
<body>
<div id="navbar">
<div id="linkbutton" class="button" onmouseover="highlightAndPersist(this);"
onmouseout="unhighlight(this);">
<b><a href="" onmouseover="persist();" onclick="return false;">Links</a></b>
</div>
</div>
<div id="menu" onmouseout="hideSoon();" onmouseover="persist();">
<a onmouseover="persist();" href="http://www.yahoo.com/">Yahoo</a><br />
<a onmouseover="persist();" href="http://www.salon.com/">Salon</a><br />
<a onmouseover="persist();" href="http://www.slashdot.org/">Slashdot</a><br />
</div>

<p>
Friends, Romans, countrymen, lend me your ears;<br />
</p>

</body>
</html>

The offsetTop, offsetLeft, and offsetHeight properties are available for any visual element on a page. I determine where to put the top of the menu by adding the height of the button to the top position of the menu. That places it immediately under the button. The left side of the menu should line up with the left side of the button, so I just used offsetLeft for the left position of the menu.

====================================================

No comments:

Post a Comment