Electric Type

Multimedia

About Us

News

Help

Advanced JavaScript Tutorial
Lesson 4

by Thau!

Page 10 — Another Way to Get at Hard-to-Reach Objects

Here's what we've learned so far about getting at an image object:

function simpleSwap()
{
	var the_image = prompt("change parrot or cheese","");
	var the_image_name = "window.document." + the_image;
	var the_image_object = eval(the_image_name);
	the_image_object.src = "ant.gif";
}

As it turns out, you can refer to images by their name in the images-associative array, like this window.document.images["parrot"].src. This is just like referring to images by their index number in the forms array, as in window.document.images[0].src. Therefore, the above code can be rewritten as


function simpleSwap()
{
	var the_image = prompt("change parrot or cheese","");
	window.document.images[the_image].src = "ant.gif";
}

You can use this trick to locate all sorts of objects. If you have a textbox in a form, like this:

<form name="the_form">
<input type="text" name="the_text_box">
</form>

You could change the text in the textbox like this:


window.document.forms["the_form"].elements["the_text_box"].value = "hello!";

Now you know several ways to access and change information in objects. Using the form example above, we can access the textbox in four different ways:
var the_form_name = "the_form";
var the_element_name = "the_text_box";

   1. window.document.forms[0].elements[0].value = "hello!";
   2. window.document.forms[the_form_name].elements[the_element_name].value = "hello!";
   3. window.document.the_form.the_text_box.value = "hello!";
   4. var the_element_string = "window.document." + the_form_name + "." + the_element_name;
      var the_element = eval(the_element_string);
      the_element_string.value = "hello!";

Whichever method you use depends on your mood, your comfort level, and what information you have available to you at the time.

And that's it for today's lesson. Let us review.

next page»


Tutorials  

User Blogs  

Teaching Tools  

Authoring  

Design  

Programming help  

Advanced Flash  

Javascript  

Glossary  

PHP Coding  

User Blogs

Screen Shots

Latest Updates

Contact Us

Valid HTML 4.01!
Valid CSS!

Breadcrumb

© ElectricType
Maintained by My-Hosts.com
Site map | Copyright | Disclaimer
Privacy policy | Acceptable Use Policy
Legal information.