PDA

View Full Version : javascript navigation menu - problem with document.getElementById is null


csb999
05-02-2009, 08:05 PM
I am relatively new to JavaScript, and I don't understand the results that I am getting. I am trying to create a navigation menu all in JS (I know, there are reasons NOT to do this). I am hiding and showing <div>s (which are submenus) when the category links are clicked. That part seems to work. I am also wanting to show/hide a navigation menu graphic as these <div>s show/hide.

The below function toggle_menu_item works as expected when I comment out the functions which toggle the navigation menu graphic (toggle_on_arrow_img, and toggle_off_arrow_img). That is to say, when I am hiding and showing the <div>s, this seems to work fine. When the graphics on/off code is included, the FIRST click works as expected. All subsequent clicks stop the script with document.getElementById(xxx) is null, when called from the toggle_img functions.

So, why would this work the first time, and not the subsequent times, and how can I fix this? I hope this is a simple question for someone more experienced than I.


function toggle_on_arrow_img( img_to_replace )
{
var imgParent = document.getElementById(img_to_replace).parentNode;
imgParent.replaceChild(arrow_on, document.getElementById(img_to_replace));
}

function toggle_off_arrow_img( img_to_replace )
{
var imgParent = document.getElementById(img_to_replace).parentNode;
imgParent.replaceChild(arrow, document.getElementById(img_to_replace));
}

function toggle_menu_item( id_to_toggle )
{
<!--- iterate over menu items, showing/hiding as necessary --->
for (var ct = 0; ct < num_menu_items; ct = ct + 1)
{
if ( id_to_toggle == menu_ids[ct][0] )
{ <!--- element to toggle --->

if ( document.getElementById(id_to_toggle).style.display == 'inline' )
{ <!--- currently expanded, hide sub menu,change graphics properties --->

toggle_off_arrow_img(menu_ids[ct][2]);
document.getElementById(id_to_toggle).style.display = 'none';

}
else
{ <!--- not currently expanded, expand and show graphic --->

document.getElementById(id_to_toggle).style.display = 'inline';
toggle_on_arrow_img(menu_ids[ct][2]);
}
}
else
{ <!--- not the selected menu, make sure it is hidden --->

toggle_off_arrow_img(menu_ids[ct][2]);
document.getElementById(menu_ids[ct][0]).style.display = 'none';
}
}

}

adios
05-03-2009, 06:14 AM
http://www.w3schools.com/JS/js_comments.asp