This code looks very bloated to me. I'm not familiar with the .item(i) method of referencing elements in an array. It may be fine, just not what I am used to. I would use captions[i] in place of captions.item(i). Also, when assigning an onclick in this manner, it must be defined as function and onclick is far preferable to onClick (less chance the script parser will reject it), for example, where you have:
Code:
nodeObj.onClick=changeBackground();
it needs to be:
Code:
nodeObj.onclick=function(){changeBackground(this);}
The red part, a reference to the individual element is not crucial but, I'll use it in just a moment.
Now, we need to think a bit about the changeBackground() function itself. Aside from your using only one equal sign in the if statement (two are required when testing equality) the code assigns this as the onclick event for each individual caption element. Do we really want the code in changeBackground() executed each time an individual caption element is clicked? Don't we want something more like this:
Code:
function changeBackground(el){
if (el.style.backgroundImage == '/minus-bg.gif')
el.style.backgroundImage = '/plus-bg.gif';
else
el.style.backgroundImage = '/minus-bg.gif';
}
Notes: Camel notation is required in place of hyphenated style properties in javascript. Not knowing your directory structure I have left '/minus-bg.gif' and like literals as is. Using the leading / means the file is in the root directory of either the domain (if live) or of the hard drive (if local). More likely you are looking for a file in the same directory as the page the script is on. If so, get rid of the leading /. If you are working across an entire site with a rich directory structure, use the exact path from the root to the image file ex:
Code:
'c:/webfiles/mysite/images/minus-bg.gif'
when working locally and:
Code:
'http://www.mysite.com/images/minus-bg.gif'
when uploading to the server. These are only example paths, change them in the code to reflect actual conditions. To summarize (with further simplifications included), this is how I would go about it:
Code:
<script type="text/javascript">
function changeBackground(el){
if (el.style.backgroundImage == 'minus-bg.gif')
el.style.backgroundImage = 'plus-bg.gif';
else
el.style.backgroundImage = 'minus-bg.gif';
}
function setBG(){
var captions = document.getElementsByTagName('caption')
for(var i = 0;i < captions.length; i++)
captions[i].onclick=function(){changeBackground(this);}
}
window.onload = setBG;
</script>
Bookmarks