Hello all,
I have script that is suppose to add an onClick event to an anchor tag based on the parent ID. That works fine when implemented by its self. My problems arise when I put it into a loop. When I click the links in side the divs the Background for that div is suppose to change color. What’s happening instead is the background for the last div (the last element of the array) is getting it’s background changed.
I am sure this is a simple problem for someone out there.
Thanks for any help!
[code=html]
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Untitled Document</title>
<script type=”text/javascript”>
function start() {
var pageSections = new Array(“horse”, “cow”, “squirl”, “rhino”);
for (var i=0; i < pageSections.length; i++) {
var elementLink = document.getElementById(pageSections[i]).getElementsByTagName(‘a’);
var elementId = pageSections[i];
//alert(elementId)
for (var x=0; x < elementLink.length; x++) {
//alert(x + elementId)
elementLink[x].onclick = function() {
//alert(x + elementId)
document.getElementById(elementId).style.backgroundColor = “#F00”;
}
}
}
}
</script>
</head>
<body onload=”start()”>
<div id=”horse” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>
<div id=”squirl” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>
<div id=”cow” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>
<div id=”rhino” style=”width:200px;height:300px;background: #EEE;”>
<a href=”#”>This is a test</a><br />
</div>
</body>
</html>