[Javascript] Code optimization

Roger Roelofs rer at datacompusa.com
Mon Aug 7 22:47:23 CDT 2006


Terry,

On Aug 7, 2006, at 9:33 PM, Terry Riegel wrote:

> Fair enough, You can look at my problematic code at:
> http://clearimageonline.com/projects/latechjs/alertparentdiv.html
>
> I do think that for posterity there should be a mechanism for 
> including the script inline as someone may be reading this a year from 
> now and the link may be long gone by then. It is sort of meaningless 
> without the code, but I do understand your concerns.
>
> As far as inserting bits of javascript inline I am sure you are 100% 
> correct, but that is little help in getting it from the inline copy to 
> the alternative without some sort of example. If I dont know how to do 
> it then the more difficult way remains the only vantage I have for 
> learning how to do it the right way.

Here's a simplistic example based on your page.  In real life, you 
would want the javascript code in a separate file.  I start by finding 
the container using the getElementById dom function.  Then I get a list 
of a elements and attach a function to the onclick event for the second 
a element.  If I wanted to, I could have attached that function to any 
element on the page, for as many elements as I want to.  The function 
figures out who got clicked and gets the parent of that element for the 
alert.  I also set the background color of the element that was clicked 
to demonstrate that it identified the correct element.

	<script type="text/javascript">
function handleClick(e) {
	var target;
	if (e) target = e.target;
	else target = window.event.srcElement;
	alert(target.parentNode);
	target.style.backgroundColor = "#ddccaa";
}

function setup() {
	var el = document.getElementById("otherstuff");
	anchors = el.getElementsByTagName("A");
	anchors[1].onclick = handleClick;
}

window.onload = setup;	
	</script>
<div class="nor" id="otherstuff">
<a href="#" >Test</a>
<a href="#" class="DIR">otherstuff</a>
</div>

I hope that was useful.


-- 
Roger Roelofs
Datacomp Appraisal Services




More information about the Javascript mailing list