Forum Moderators: open
Im trying to make some simple boxes that when clicked on drop down to give the user more information. This is obviously easy enough BUT I am really surprised with the issues I'm having in closing the other divs down when one opens.
Im using this code snippet:
<script type="text/javascript">
function showMe (it)
{
for (i=0;i<=2;i++) {
if (i == it) {
document.getElementById('div_'+it).style.display ='block';}
else {
document.getElementById('div_'+i).style.display ='none';}
}
}
</script> and the link is :
<a href="javascript:showMe(1);">China</a> Can anyone see any obvious issues with this code? Javascript really isn't my language - I'm mor eused to idiot based Python.
Thanks
Ad
adhoc01
Posts: 3
Joined: Wed May 28, 2008 12:51 pm
1) i is not defined using var, it should be, otherwise it has global scope beyond the function. This can really mess things up.
2) Type coercion is being used to change both "it" and "i" from numbers to strings, this too, can mess things up.
Try this:
function showMe(it)
var i, itStr=it.toString();
{
for (i=0;i<=2;i++) {
if (i == it) {
document.getElementById('div_'+itStr).style.display ='block';}
else {
document.getElementById('div_'+i.toString()).style.display ='none';}
}
}
</script>
Try it and see.
Also, I'm curious - is your function bombing in more than one browser?
Do you have IE, for instance, set up to detect all script errors?