JavaScript - Help Closing While Loop
So this is what I have so far:
Code: import java.util.Random; public class lotteryGame { public static void main(String args[]) throws Exception { int n=0; // counter for the amount of times played int t=0; // total amount of winnings int i=0; // number of matches int a; // first guess int b; // second guess int c; // third guess int d; // first number in the lottery int e; // second number in the lottery int f; // third number in the lottery Random rand = new Random(); while (n<100) // play the game for 100 times { a=rand.nextInt(9) + 1; // assign a random number to a b=rand.nextInt(9) + 1; c=rand.nextInt(9) + 1; System.out.println("Lottery Number"+a+b+c); d=rand.nextInt(9) + 1; e=rand.nextInt(9) + 1; f=rand.nextInt(9) + 1; System.out.println("Your guess"+d+e+f); if (a==d){ i=i+1; System.out.println(a+"is a match"); d=d+10; // if a=d then d is taken out of the range (1-9) } else if (a==e){ System.out.println(a+"is a match"); i=i+1; e=e+10; } else if (a==f){ System.out.println(a+"is a match"); i=i+1; f=f+10; } if (b==d){ System.out.println(b+"is a match"); i=i+1; d=d+10; } else if (b==e){ System.out.println(b+"is a match"); i=i+1; e=e+10; } else if (b==f){ System.out.println(b+"is a match"); i=i+1; f=f+10; } if (c==d){ System.out.println(c+"is a match"); i=i+1; d=d+10; } else if (c==e){ System.out.println(c+"is a match"); i=i+1; e=e+10; } else if (c==f){ System.out.println(c+"is a match"); i=i+1; f=f+10; } if (i==3){ if (a==d-10&&b==e-10&&c==f-10){ t=t+10000; System.out.println("You win!!!"); } else{ t=t+1000; System.out.println("You had 3 matches! You win $1000"); } } if (i==2){ t=t+50; System.out.println("You had 2 matches! You win $50"); } if (i==1){ t=t+10; System.out.println("You had 1 match! You win $10"); } } n=n+1; i=0; } } I don't know what is wrong with the program, It compiles fine but when I run it, it never stops. =/ I figure that Code: n=n+1 would be a counter to stop the while loop. Where do I place it so it can count everytime it runs. Or, What do I need to add in order for the program to stop running after 100 times? Thank You. =] Similar Tutorialsokay, im using this script to close a DIV, can i somehow link it so that it loads main.swf when the div is closed? Now the SWF is running in the bg. Code: <script language=javascript> <!-- function hideDiv(){ if(document.getElementById('Div').style.display != "none") { document.getElementById('Div').style.display = "none"; }} //--> </script> Code: <a href=# onclick="javascript:hideDiv();">Close</a> Say you have a document with 2 frames with 2 buttons in one of the frames. If one button opens a window, how can you make the other button close it?
Hi, im thinking about something like this, is this the correct way to do this. Code: function run_timout() { timout = setTimeout(closethewindow, 3000); } function closethewindow() { alert("Your time is up!"); window.close('mywindow'); } I think this is a simple problem, but lets see... As the title suggests, I'm building a menu where when the user clicks on their username, a menu slides down. That part is easy. Using jQuery, I'm using slideToggle so when they click it again it moves back up. But what I'd also like to do is make it so if they leave the menu "area" (eg, are not on the username or the menu) I'd like the menu to slide back up. I tried Code: $('#userLink, #userMenu').mouseout(function () { $('#userMenu').slideUp('fast'); }); But there is the obvious flaw of when they mouse from the username to the menu, they leave the username and the menu closes back up. Anyone have thoughts on how this is/can be done? Is there a way to check what element the mouse is on at any given time? My other thought was to have a function set on timeout that would check if its on one of the accepted elements, and if not, close the menu and disengage the timeout. Hi there all, Trying to adapt a bit of Code, but failing wonderfully! I'm writing in Cold Fusion, but using a little java script to create the sliding effect. It's from a sliding open list function in another site, and I tried to just hack my current needs in there. Code: <script> function DC_ShowHideMoreWebsites(id) { if( document.getElementById( "contentsections2").style.display=="none" ) { Effect.BlindDown( "contentsections2"); return false; } else { Effect.SlideUp( "contentsections2" ); return false; } } </script> is followed by Code: <p id="moreScreenshots"><a href="#" onclick="DC_ShowHideMoreWebsites"; return false;">More Website Examples</a></p> I've tested the script, div and the DB call by just calling it with Code: <p id="moreScreenshots"><a href="#" onclick="Effect.BlindDown('contentsections2'); return false;">More Website Examples</a></p> And that works fine. I've never coded in Java, hence the problem! any help appreciated I have a lightbox pop up on my homepage. I'm curious if there's a way to automatically close the pop up after 5 seconds or so. For some readon onClose kept popping in my head, but I'm pretty sure that's not correct. Thanks. Code: !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:// www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Lightbox Example</title> </head> <body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.4/jquery.min.js"></script> <script type="text/javascript" src="/lightbox/ jquery.mousewheel-3.0.4.pack.js"></script> <script type="text/javascript" src="/lightbox/ jquery.fancybox-1.3.4.pack.js"></script> <link rel="stylesheet" type="text/css" href="/lightbox/fancybox/ jquery.fancybox-1.3.4.css" media="screen" /> <script type="text/javascript"> $(document).ready(function() { $("a#onload").fancybox({ 'frameHeight': 390, 'frameWidth': 640, 'hideOnContentClick': false, 'easingIn': 2000 }).trigger('click'); }); </script> <div id="lightbox_content" style="display:none"> <div id="data"> <img src="/lightbox/donate.jpg" alt="Support Today!"> <h1>Pledge Your Support Today!!</h1> </div> </div> <a id="onload" href="#data"></a> </body> </html> Hello all, I built a javascript accordian menu that works very well. However, after a menu is opened, I have to click on another menu to close the current one. I would like to be able to toggle opening and closing of a menu without having to interact with other menus. I appreciate any help! Here is the Javascript code: Code: var expandFirstItemAutomatically = false; // Expand first menu item automatically ? var initMenuIdToExpand = false; // Id of menu item that should be initially expanded. the id is defined in the <li> tag. var expandMenuItemByUrl = true; // Menu will automatically expand by url - i.e. if the href of the menu item is in the current location, it will expand var initialMenuItemAlwaysExpanded = true; var dhtmlgoodies_slmenuObj; var divToScroll = false; var ulToScroll = false; var divCounter = 1; var otherDivsToScroll = new Array(); var divToHide = false; var parentDivToHide = new Array(); var ulToHide = false; var offsetOpera = 0; if(navigator.userAgent.indexOf('Opera')>=0)offsetOpera=1; var slideMenuHeightOfCurrentBox = 0; var objectsToExpand = new Array(); var initExpandIndex = 0; var alwaysExpanedItems = new Array(); var dg_activeItem = null; function popMenusToShow() { var obj = divToScroll; var endArray = new Array(); while(obj && obj.tagName!='BODY'){ if(obj.tagName=='DIV' && obj.id.indexOf('slideDiv')>=0){ var objFound = -1; for(var no=0;no<otherDivsToScroll.length;no++){ if(otherDivsToScroll[no]==obj){ objFound = no; } } if(objFound>=0){ otherDivsToScroll.splice(objFound,1); } } obj = obj.parentNode; } } function showSubMenu(e,inputObj) { if(this && this.tagName)inputObj = this.parentNode; if(inputObj && inputObj.tagName=='LI'){ divToScroll = inputObj.getElementsByTagName('DIV')[0]; for(var no=0;no<otherDivsToScroll.length;no++){ if(otherDivsToScroll[no]==divToScroll)return; } } hidingInProcess = false; if(otherDivsToScroll.length>0){ if(divToScroll){ if(otherDivsToScroll.length>0){ popMenusToShow(); } if(otherDivsToScroll.length>0){ autoHideMenus(); hidingInProcess = true; } } } if(divToScroll && !hidingInProcess){ divToScroll.style.display=''; otherDivsToScroll.length = 0; otherDivToScroll = divToScroll.parentNode; otherDivsToScroll.push(divToScroll); while(otherDivToScroll && otherDivToScroll.tagName!='BODY'){ if(otherDivToScroll.tagName=='DIV' && otherDivToScroll.id.indexOf('slideDiv')>=0){ otherDivsToScroll.push(otherDivToScroll); } otherDivToScroll = otherDivToScroll.parentNode; } ulToScroll = divToScroll.getElementsByTagName('UL')[0]; if(divToScroll.style.height.replace('px','')/1<=1)scrollDownSub(); } if(e || inputObj) { if(dg_activeItem) { dg_activeItem.className = dg_activeItem.className.replace('coursefinder_activeItem',''); } var aTags = inputObj.getElementsByTagName('A'); if(aTags.length>0) { aTags[0].className = aTags[0].className + ' coursefinder_activeItem'; dg_activeItem = aTags[0]; if(aTags[0].href.indexOf('#') == -1 || aTags[0].href.indexOf('#') < aTags[0].href.length-1){ return true; } } } return false; } function autoHideMenus() { if(otherDivsToScroll.length>0){ divToHide = otherDivsToScroll[otherDivsToScroll.length-1]; parentDivToHide.length=0; var obj = divToHide.parentNode.parentNode.parentNode; while(obj && obj.tagName=='DIV'){ if(obj.id.indexOf('slideDiv')>=0)parentDivToHide.push(obj); obj = obj.parentNode.parentNode.parentNode; } var tmpHeight = (divToHide.style.height.replace('px','')/1 - slideMenuHeightOfCurrentBox); if(tmpHeight<0)tmpHeight=0; if(slideMenuHeightOfCurrentBox)divToHide.style.height = tmpHeight + 'px'; ulToHide = divToHide.getElementsByTagName('UL')[0]; slideMenuHeightOfCurrentBox = ulToHide.offsetHeight; scrollUpMenu(); }else{ slideMenuHeightOfCurrentBox = 0; showSubMenu(); } } function scrollUpMenu() { var height = divToHide.offsetHeight; height-=15; if(height<0)height=0; divToHide.style.height = height + 'px'; for(var no=0;no<parentDivToHide.length;no++){ parentDivToHide[no].style.height = parentDivToHide[no].getElementsByTagName('UL')[0].offsetHeight + 'px'; } if(height>0){ setTimeout('scrollUpMenu()',0); }else{ divToHide.style.display='none'; otherDivsToScroll.length = otherDivsToScroll.length-1; autoHideMenus(); } } function scrollDownSub() { if(divToScroll){ var height = divToScroll.offsetHeight/1; var offsetMove =Math.min(15,(ulToScroll.offsetHeight - height)); height = height +offsetMove ; divToScroll.style.height = height + 'px'; for(var no=1;no<otherDivsToScroll.length;no++){ var tmpHeight = otherDivsToScroll[no].offsetHeight/1 + offsetMove; otherDivsToScroll[no].style.height = tmpHeight + 'px'; } if(height<ulToScroll.offsetHeight)setTimeout('scrollDownSub()',0); else { divToScroll = false; ulToScroll = false; if(objectsToExpand.length>0 && initExpandIndex<(objectsToExpand.length-1)){ initExpandIndex++; showSubMenu(false,objectsToExpand[initExpandIndex]); } } } } function initSubItems(inputObj,currentDepth) { divCounter++; var div = document.createElement('DIV'); // Creating new div div.style.overflow = 'hidden'; div.style.position = 'relative'; div.style.display='none'; div.style.height = '1px'; div.id = 'slideDiv' + divCounter; div.className = 'slideMenuDiv' + currentDepth; inputObj.parentNode.appendChild(div); // Appending DIV as child element of <LI> that is parent of input <UL> div.appendChild(inputObj); // Appending <UL> to the div var menuItem = inputObj.getElementsByTagName('LI')[0]; while(menuItem){ if(menuItem.tagName=='LI'){ var aTag = menuItem.getElementsByTagName('A')[0]; aTag.className='slMenuItem_depth'+currentDepth; var subUl = menuItem.getElementsByTagName('UL'); if(subUl.length>0){ initSubItems(subUl[0],currentDepth+1); } aTag.onclick = showSubMenu; } menuItem = menuItem.nextSibling; } } function initSlideDownMenu() { dhtmlgoodies_slmenuObj = document.getElementById('coursefinder'); dhtmlgoodies_slmenuObj.style.visibility='visible'; var mainUl = dhtmlgoodies_slmenuObj.getElementsByTagName('UL')[0]; var mainMenuItem = mainUl.getElementsByTagName('LI')[0]; mainItemCounter = 1; while(mainMenuItem){ if(mainMenuItem.tagName=='LI'){ var aTag = mainMenuItem.getElementsByTagName('A')[0]; aTag.className='slMenuItem_depth1'; var subUl = mainMenuItem.getElementsByTagName('UL'); if(subUl.length>0){ mainMenuItem.id = 'mainMenuItem' + mainItemCounter; initSubItems(subUl[0],2); aTag.onclick = showSubMenu; mainItemCounter++; } } mainMenuItem = mainMenuItem.nextSibling; } if(location.search.indexOf('mainMenuItemToSlide')>=0){ var items = location.search.split('&'); for(var no=0;no<items.length;no++){ if(items[no].indexOf('mainMenuItemToSlide')>=0){ values = items[no].split('='); showSubMenu(false,document.getElementById('mainMenuItem' + values[1])); initMenuIdToExpand = false; } } } else if(expandFirstItemAutomatically>0 ){ if(document.getElementById('mainMenuItem' + expandFirstItemAutomatically)){ showSubMenu(false,document.getElementById('mainMenuItem' + expandFirstItemAutomatically)); initMenuIdToExpand = false; } } if(aTag.className.indexOf("active") == -1) { aTag.onclick = showSubMenu; } else { aTag.onclick = scrollUpMenu; } mainItemCounter++; } if(expandMenuItemByUrl) { var aTags = dhtmlgoodies_slmenuObj.getElementsByTagName('A'); var currentLocation = location.pathname; for(var no=0;no<aTags.length;no++){ var hrefToCheckOn = aTags[no].href; if(hrefToCheckOn.indexOf(currentLocation)>=0 && hrefToCheckOn.indexOf('#')<hrefToCheckOn.length-1){ aTags[no].className = aTags[no].className + ' coursefinder_activeList'; initMenuIdToExpand = false; var obj = aTags[no].parentNode; while(obj && obj.id!='coursefinder'){ if(obj.tagName=='LI'){ var subUl = obj.getElementsByTagName('UL'); if(initialMenuItemAlwaysExpanded)alwaysExpanedItems[obj.parentNode] = true; if(subUl.length>0){ objectsToExpand.unshift(obj); } } obj = obj.parentNode; } showSubMenu(false,objectsToExpand[0]); break; } } } if(initMenuIdToExpand) { objectsToExpand = new Array(); var obj = document.getElementById(initMenuIdToExpand) while(obj && obj.id!='slidedown_menu'){ if(obj.tagName=='LI'){ var subUl = obj.getElementsByTagName('UL'); if(initialMenuItemAlwaysExpanded)alwaysExpanedItems[obj.parentNode] = true; if(subUl.length>0){ objectsToExpand.unshift(obj); } } obj = obj.parentNode; } showSubMenu(false,objectsToExpand[0]); } } Hi! I'm working on a website where I need some help with open and closing divs using javascript. This is the website: clashjeans.se/test/styles.html As you can see I'm using a javascript to open each jeans style link, I don't know if this is the best way to do it, but it's how I've done it so far. If you click the "Frankie style link" at the bottom the div called Frankie will show and you will see a little image in that div that says "next wash". What I would like this link to do is to close the frankie div and open up another wich looks almost the same as the previous, the only thing that will change is the pictures actually. Please help me solve this problem, any suggestion about how to make this work will be highly appreciated! Is there a way to capture the event of the user closing the browser??
Hello all, I am trying to close a window when I press a link using javascript. The code is simple... Code: <a href="" onclick="window.close()">Close this window</a> This works as well, and I know that it will work only on windows opened by javascript. That's ok as well. My question is that in Firefox, I can open a link a new tab. So I open a new tab by clicking on a link like this... Code: <a href="somepage.html" target="_blank">OPEN</a> Now when I try to close this tab using javascript, after closing it refreshes the page. This I know is happening because, I did href="". What's the workaround for this problem.... I'm trying to get my form to save a user's data via cookies. I found a script at http://www.fijiwebdesign.com/blog/re...ubmission.html, and it only seems to work if you refresh the page, but not if you close out the browser and restart. Code: <form action="process-contact.php" id="contact" method="post"> Name: <input type="text" name="name"/> <br />Email: <input type="text" name="email"/> <br />Message: <textarea name="message"></textarea> <br /><input type="submit" value="Submit"/> </form> <script type="text/javascript"> window.onload = function() { rememberFormInputs('contact', 'input-'); } /** * Set a cookie * @param string cookie name * @param string cookie value * @param string cookie expiration counter in days * @param string cookie path * @param string cookie domain * @param bool secure? */ function setCookie(name, value, expires, path, domain, secure) { var today = new Date(); today.setTime(today.getTime()); if (expires) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date(today.getTime() + (expires)); document.cookie = name+"="+escape(value) + ((expires) ? ";expires="+expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : ""); } /** * Get a cookie value * @param string cookie name */ function getCookie(name) { var start = document.cookie.indexOf(name + "="); var len = start + name.length + 1; if ((!start) && (name != document.cookie.substring(0, name.length))) { return null; } if (start == -1) return null; var end = document.cookie.indexOf(";", len); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(len, end)); } /** * Remebers form inputs after you fill them in * @param string form id to remember fields * @param string a prefix to prepend to all cookie names. (prevent naming conflicts) */ function rememberFormInputs(form_id, prefix) { var form = document.getElementById(form_id); var els = document.getElementsByTagName('input'); for (var i = 0; i < els.length; i++) { var el = els.item(i); if (el.type == 'text') { el.onblur = function() { var name = this.name; var value = this.value; setCookie(prefix + name, value); }; var old_value = getCookie(prefix + el.name); if (old_value && old_value != '') { el.value = old_value; } } } } </script> The demo on the site I got this code from is a broken link. I would really appreciate any and all help to get this resolved. I know cookies are suppose to save even after closing out the browser. Hello, Here is what I have: a regular main window that opens a small pop-up for preview purposes. This pop-up window has a text link to close it and a text link to close it and reach a page with more detail in the main window. I have been trying an infinite number of things so far and I cannot get this last link to work in Opera 10. All workarounds are just fine in FF 3 and IE 8. Here is the function called when clicking the link to "close and go": Code: <script type="text/javascript"> function fermer_extrait() { window.opener.location='http://www.wereIwantToGo.com'; window.close(); } </script> I have tried the same thing with Code: window.opener.location.href='http://www.wereIwantToGo.com'; and some other window property like "outerWidth" for testing purposes. In every case, Opera doesn't do anything when I click that link and I get this error: Code: JavaScript - http://www.mypage.php Event thread: click Error: name: ReferenceError message: Security error: attempted to write protected variable 'href' stacktrace: Line 1 of function script window.opener.location.href='http://www.wereIwantToGo.com'; window.close() "protected variable" will change according to the attempt I made (href, location, outerwidth). I'm gessing there is something very strict in the way Opera handles javascript. I'm a beginner and I have reached my limits. This is where I ask for help... So, how can I get that pop-up to close and get the main window to change location? Thanks in advance for any help! Hi, I'm having troube closing the main Internet Explorer window using a script called from a right click menu. The code I'm using is: Code: <script language="JavaScript"> var oWindow = window.external.menuArguments; oWindow.close(); </script> When the script calls, windows prompts to close the window, but when 'yes' is clicked the Alert sound sounds and the window remains open! If the script is called from a button on the page it will close, but I want to close any page on the internet using a right click! All help will be gratefully received. Dave. Folks I'm using the code below to create a pop-up search box that finds text strings on a contents page. The contents page contains a list of hyperlinks each of which opens a PDF document in the same window. The search box does exactly what it's intended to do, but the problem is this: if the user clicks on "Find next" or "Find previous" once the PDF document is open, an error occurs; the same error occurs if the user then navigates back to the contents page and clicks on "Find next" or "Find previous". I'm thinking the solution must be to get the search box to close as soon as the PDF document opens, but how do I achieve this? Thanks Remster Code: <html> <head> <title>Search this page</title> <script language=JavaScript> var rng = dialogArguments.document.body.createTextRange(); rng.collapse(); function findnext(){ if (document.all.strSearch.value.length < 1) { alert("Please enter text to find."); document.frmSearch.strSearch.focus(); } else { var searchval = document.all.strSearch.value; rng.collapse(false); if (rng.findText(searchval, 1000000000)) { rng.select(); } else { alert("Finished searching page."); rng.select(false); document.frmSearch.strSearch.focus(); } } } function findprevious(){ if (document.all.strSearch.value.length < 1) { alert("Please enter text to find."); document.frmSearch.strSearch.focus(); } else { var searchval = document.all.strSearch.value; rng.collapse(true); if (rng.findText(searchval, 1000000000, 1)) { rng.select(); } else { alert("Finished searching page."); rng.select(false); document.frmSearch.strSearch.focus(); } } } </script> </head> <body bgColor=buttonface> <form name=frmSearch onsubmit="findnext();return false;" onsubmit="findprevious();return false;" action="" method=post> <table cellSpacing=0 cellPadding=0 border=0> <tr> <td style="font-size: 12px; font-family: Arial" vAlign=top noWrap align=left> <input id=strSearch style="margin-left: 15px; margin-top: 14px; width: 249;" name=strSearch><br> <button style="margin-left: 15px; margin-top: 12px; width: 120px; height: 25px;" accessKey=f onclick=findnext(); name=btnFindNext>Find next</button> <button style="margin-left: 9px; margin-top: 12px; width: 120px; height: 25px;" accessKey=f onclick=findprevious(); name=btnFindPrevious>Find previous</button></br> </td> </tr> </table> </form> </body> </html> Hi All, I have to know whether we can track the direct browser closing event by Javascript. I have tried with window.unload & window.onbeforeunload, but I was not get full satisfaction with those ones. Please let me know if anybody have any kind of solutions other than those specified above. advance thanks... Hi, I have an input element (textbox) on a webpage, and capture the onblur event of the input (textbox) control to do validation. My problem is that when the page is closed or the user click on another window the onblur event of my textbox gets called too. I need the onblur event handler to be called only when the textbox loses focus b/c another element on the SAME webpage gets focus, but not when the user clicks on another window or closes the browser window. What is the right way to accomplish this? Thanks in advance, Richard I have home page with session close button and 10 child window link and i am opening all child window.All child windows should close after clicking on session close button. Code bellow <html> <script type="text/javascript"> openWins = []; curWin = 0; function openWin(page) { openWins[curWin++] = window.open(page,'_blank'); } function closeAll() { for(var i=0; i<openWins.length; i++) if (openWins[i] && !openWins[i].closed) openWins[i].close(); } window.onunload = closeAll; </script> <body > <input type="button" onClick="openWin('http://www.google.com');" value="Open PopUps"> <input type="button" onClick="closeAll('http://www.google.com');" value="Close PopUps"> </body> </html> How could I open a page/popup after closing one? The objective is to log the user out if they haven't Logged out or clicked Logout. I am sure there is a simple way to do this. None of my ideas work. The only answer I could come with (after testing the whole day...) IE(any version), Firefox, and other browsers don't support this idea, due to the fact that the user clicked close and you can't impose things on them. Hi, I am using a wordpress jquery based plugin. TheThe Sliding panels. You can see the jquery he - http://www.get-me-heard.com/wp-conte...jquery.ttsp.js The panel currently auto-opens when the page loads. Which is what I want, however I would like it so that once a user has clicked to close the panel, for it to stay closed even when navigating pages, until they decide to click open again. I would also need the cookie flushed when they leave the website so that the next time they return the panels auto open again. Essentially I just dont want the users to have to click close every time they navigate throughout the website if they don't want to see the panels. NOTE: The plugin has several panels which you can choose from. I am only using the left panel and the right panel. They are all controlled within the jquery. Thanks! Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. |